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

Android TableLayout 數據列表的回顯與清空實現

編輯:關於 Android 程式設計

在使用 TableLayout 構建表格樣式的數據列表時,經常會遇到「重新加載數據」的場景。這時候,必須先把已有的子行清空,再重新填充,否則就會出現數據重複堆疊的問題。

這裡有一個關鍵細節:在移除子元素時,一定要「從後往前」刪除,這樣才能避免索引錯位導致的異常。下面這段代碼演示了如何實現數據列表的回顯與清空。

復制代碼 代碼如下:

//數據列表的回顯
public void shujuList(){
List<Customer> customerList = dao.findALL();
TableLayout tl = (TableLayout) findViewById(R.id.tlLayout);
Log.i(">>>", String.valueOf(tl.getChildCount()));
int j = tl.getChildCount();
if(j>1){
/*for(int i=0;i<j;i++){
tl.removeView(tl.getChildAt(j-i));//必須從後面減去子元素
}*/
for(int i=j;i>0;i--){
tl.removeView(tl.getChildAt(i));//必須從後面減去子元素
}
}
TableRow row = null;
for(Customer c : customerList){
row = new TableRow(this);
//id
TextView tvId = new TextView(this);
tvId.setText(c.id + "");
row.addView(tvId);
//name
TextView tvName = new TextView(this);
tvName.setText(c.name);
row.addView(tvName);
//age
TextView tvAge = new TextView(this);
tvAge.setText(c.teleNumber + "");
row.addView(tvAge);
tl.addView(row);
}
}

整段邏輯可以拆成兩部分:先遍歷並移除現有的 TableRow,再透過查詢到的數據集合逐條構建新的行並添加進 TableLayout。這樣就能實現列表的即時刷新與回顯。

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