我已经从数组列表中动态创建了一个表
for (int i = 0; i < arrayList.size(); i++) {
TextView name = new TextView(this);
TextView time = new TextView(this);
TableRow row = new TableRow(this);
// Set event name and remaining time
name.setText(arrayList.get(i).name);
time.setText("...");
// Add text views to row
row.addView(time, layoutParams);
row.addView(name, layoutParams);
// Add row to table
tableLayout.addView(row, i);
}
现在,如果我想在条件下编辑或删除某些行,我将不得不访问该行,但是如何?
outerloop:
for(int i = 0; i < arrayList.size(); i++ ) {
if(// row's time <= 0 ...) {
tableLayout.removeViewAt(i); // this doesn't seem to work properly
// it removes the wrong rows
}
else {
// ...
break outerloop;
}
}
由于某种原因tableLayout.removeViewAt(i);
删除了错误的行。或者,我更喜欢编辑该行name
,但原则适用,我只需找到一种方法来访问表格行。无论如何?
答案 0 :(得分:2)
像这样创建你的表:
ArrayList<TableRow> rows = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
TextView name = new TextView(this);
TextView time = new TextView(this);
TableRow row = new TableRow(this);
rows.add(row);
// Set event name and remaining time
name.setText(arrayList.get(i).name);
time.setText("...");
// Add text views to row
row.addView(time, layoutParams);
row.addView(name, layoutParams);
// Add row to table
tableLayout.addView(row, i);
}
当你想要删除一行时,你可以通过它在ArrayList中的索引来做到这一点:
row = rows.get(i);
table.removeView(row);
rows.remove(i);
如果您想删除多行,这可能是您的解决方案:
ArrayList<TableRow> removeRows = new ArrayList<>();
for(int i = 0; i < rows.size(); i++) {
if(....) {
removeRows.add(rows.get(i));
}
}
// now delete those rows
for(TableRow remove : removeRows) {
tableLayout.removeView(row);
rows.remove(remove);
}
我希望这适合你!