Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android TableLayout 動態刷新:先清空再回填資料列表

編輯:關於 Android 程式設計

用 TableLayout 呈現資料列表時,最常遇到的需求就是「刷新」——當底層資料有變動,需要重新把最新內容畫上去。如果每次刷新都直接 addView,舊的資料列會一直累積,畫面上就會出現重複的資料。因此正確的做法是:在回填新資料之前,先把現有的子檢視清乾淨。

核心觀念:先清空,再新增

整個流程可以拆成兩個步驟。第一步是取得 TableLayout 目前的子檢視數量,逐一把它們移除;第二步則是遍歷新的資料集合,為每一筆資料建立一個 TableRow 並加入。

這裡藏著一個很容易被忽略的細節:移除子元素時必須「從後往前」刪除。原因是每當你呼叫一次 removeView,後續元素的索引都會往前遞移;若從頭開始刪,索引很快就會錯位甚至越界。因此迴圈應該從最後一個索引往回走。

參考實作

public void shujuList() {
    List<Customer> customerList = dao.findALL();
    TableLayout tl = (TableLayout) findViewById(R.id.tlLayout);

    // 先移除所有舊的資料列(僅保留可能存在的標題列)
    int childCount = tl.getChildCount();
    for (int i = childCount - 1; i > 0; i--) {
        tl.removeViewAt(i); // 從後往前刪,避免索引錯位
    }

    // 再依序填入新資料
    for (Customer c : customerList) {
        TableRow row = new TableRow(this);

        TextView tvId = new TextView(this);
        tvId.setText(c.id + "");
        row.addView(tvId);

        TextView tvName = new TextView(this);
        tvName.setText(c.name);
        row.addView(tvName);

        TextView tvAge = new TextView(this);
        tvAge.setText(c.teleNumber + "");
        row.addView(tvAge);

        tl.addView(row);
    }
}

相較於逐一 removeView,使用 removeViewAt(i) 搭配反向索引語意更清楚,也不容易出錯。若你的列表資料量很大,也可以考慮改用 ListView 或 RecyclerView 搭配 Adapter,它們天生就是為「資料驅動畫面」而設計,能省去大量手動增刪檢視的工作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved