在函數中動態向 `TableLayout` 追加行,每行含一個 `ImageView`。
public void addRowWithImage(Context context, TableLayout table, int imageResId) {
// 1. 創建 TableRow
TableRow row = new TableRow(context);
row.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT
));
row.setGravity(Gravity.CENTER);
row.setPadding(0, 16, 0, 16); // 上下間距
// 2. 創建 ImageView
ImageView iv = new ImageView(context);
iv.setImageResource(imageResId);
iv.setAdjustViewBounds(true); // 保持比例
iv.setMaxWidth(200); // 限制最大寬度
iv.setLayoutParams(new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT,
1f // weight 平均分配
));
iv.setPadding(16, 0, 16, 0);
// 3. 添加到行,行添加到表
row.addView(iv);
table.addView(row);
}
<TableLayout
android:id="@+id/tl_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
android:orientation="vertical" />
TableLayout tl = findViewById(R.id.tl_container);
addRowWithImage(this, tl, R.drawable.ic_launcher);
addRowWithImage(this, tl, R.drawable.ic_menu_camera);