【问题标题】:Updating some rows dynamically in TableLayout在 TableLayout 中动态更新一些行
【发布时间】:2015-05-12 05:45:53
【问题描述】:

我正在动态地向我的TableLayout 添加行,并且每一行都有多个TextView

我想循环我的TableLayout 中的每一行,并且我想更新一些行(不是每一行),例如我的行中TextView 的文本。我该如何管理?

【问题讨论】:

  • 发布您尝试过的代码(如果有)?

标签: android dynamic rows tablelayout


【解决方案1】:

循环遍历 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。

【讨论】:

  • 首先感谢您的回复。但我不知道如何循环遍历 TableLayout 的子项(我的子项是 TableRows)。然后,另一个问题是我正在为每个 TableRow 动态添加 TableRows 和 TextViews、CheckBoxes。如何获取特定 TableRow 中特定 TextView 的 id?我问的是你告诉了“findViewById”。
  • 谢谢,我会试试的,但据我所见,它非常合乎逻辑。
  • 我也想了解如何像这样在 ListView 中循环?我想从代码中分配复选框 id,例如 checkbox1、checkbox2,然后我还想控制 1 到 100,例如,如果它们被选中。我该怎么做?
  • 我正在使用你的代码,但是有一个问题:tableLayout.getChildCount() 返回行数和2的乘积。例如我有5行,每行有2个TextView和 1 个复选框。我不明白为什么 getChildCount() 返回 10。当我像 TableRow row = (TableRow) tableLayout.getChildAt(0) 这样从 tableLayout 获取第一个孩子时,它正在工作,但是 getChildAt(1) 返回一个 id 为 -1 的愚蠢行。对于所有奇数,组件的 id 返回 -1。
  • -1 id'ed 行可能是行之间的分隔符?
【解决方案2】:

我建议使用 setTag 方法快速到达特定行和行内的视图。

例如,假设您在某个列中有一个 CheckBox,表示“isSomethingEnabled”。创建 CheckBox 时,执行 setTag("foo")。

在行上也使用setTag,比如setTag("rowKey")

快速到达特定行

TableRow tRow = (TableRow) tLayout.findViewWithTag("rowKey");

并快速找到特定的孩子

查看 v = tRow.findViewWithTag("foo");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多