首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Android TableLayout 動態添加 TableRow + ImageView:Java 代碼構建視圖層級完整範例

     編輯:程式設計綜合問答

在函數中動態向 `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);
}

XML 佈局預留容器

<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);

避坑提醒

  • 動態創建的 View **必須**設置 `LayoutParams`,否則不顯示或佈局崩潰。
  • `TableRow.LayoutParams` 的構造函數參數順序:`width, height, weight`。
  • 大量動態添加建議改用 `RecyclerView` + `GridLayoutManager`,性能與內存友好得多。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved