【发布时间】:2015-05-12 05:45:53
【问题描述】:
我正在动态地向我的TableLayout 添加行,并且每一行都有多个TextView。
我想循环我的TableLayout 中的每一行,并且我想更新一些行(不是每一行),例如我的行中TextView 的文本。我该如何管理?
【问题讨论】:
-
发布您尝试过的代码(如果有)?
标签: android dynamic rows tablelayout
我正在动态地向我的TableLayout 添加行,并且每一行都有多个TextView。
我想循环我的TableLayout 中的每一行,并且我想更新一些行(不是每一行),例如我的行中TextView 的文本。我该如何管理?
【问题讨论】:
标签: android dynamic rows tablelayout
循环遍历 TableLayout 的子级,它们应该是 TableRows(或其他布局) - 跳过您不想更新的那些。循环或 findViewById 的 TableRow (或其他)的孩子,这将是你的 TextViews
当您将 TextView / CheckBox 添加到 TableRow 时,您可以使用 setId(R.id.id_of_the_view) 设置视图的 id(您可能希望将其添加到 res/values/ids.xml 文件中)。
然后像这样循环:
TableLayout tableLayout = null;
for(int n = 0, s = tableLayout.getChildCount(); n < s; ++n) {
TableRow row = (TableRow)tableLayout.getChildAt(n);
TextView name = (TextView)row.findViewById(R.id.tv_name);
}
由于您使用的是 row.findViewById,因此您正在寻找特定行中的特定 ID。
【讨论】:
TableRow row = (TableRow) tableLayout.getChildAt(0) 这样从 tableLayout 获取第一个孩子时,它正在工作,但是 getChildAt(1) 返回一个 id 为 -1 的愚蠢行。对于所有奇数,组件的 id 返回 -1。
我建议使用 setTag 方法快速到达特定行和行内的视图。
例如,假设您在某个列中有一个 CheckBox,表示“isSomethingEnabled”。创建 CheckBox 时,执行 setTag("foo")。
在行上也使用setTag,比如setTag("rowKey")
快速到达特定行
TableRow tRow = (TableRow) tLayout.findViewWithTag("rowKey");
并快速找到特定的孩子
查看 v = tRow.findViewWithTag("foo");
【讨论】: