【问题标题】:How to refer to TableLayout cells in code如何在代码中引用 TableLayout 单元格
【发布时间】:2018-11-12 07:31:32
【问题描述】:

我在我的 xml 中定义了一个 TableLayout,其中包含三列四行加上一个标题行。 每列包含一个 TextView。

    <TableLayout
    android:id="@+id/inventory"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:stretchColumns="*"
    <TableRow>
        <TextView
            android:text="Item"/>
        <TextView
            android:text="Quantity"/>
        <TextView
            android:text="Units"/>
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/inventorycell10"
        <TextView
            android:id="@+id/inventorycell11"
        <TextView
            android:id="@+id/inventorycell12"
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/inventorycell20"
        <TextView
            android:id="@+id/inventorycell21"
        <TextView
            android:id="@+id/inventorycell22"
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/inventorycell30"
        <TextView
            android:id="@+id/inventorycell31"
        <TextView
            android:id="@+id/inventorycell32"
    </TableRow>
    <TableRow>
        <TextView
            android:id="@+id/inventorycell40"
        <TextView
            android:id="@+id/inventorycell41"
        <TextView
            android:id="@+id/inventorycell42"
    </TableRow>
</TableLayout>

有没有办法在代码中引用 TextViews,而不必单独标识它们。我在想可能有办法从表格视图中获取行/列视图。

-弗林克

【问题讨论】:

    标签: android


    【解决方案1】:

    您可以使用ViewGroup#getChildAtViewGroup#getChildCountgetChildAt 在您的根目录上TableLayout 将允许您获取TableRows,随后在TableRows 上调用它将允许您访问TextViews。

    【讨论】:

      【解决方案2】:

      我喜欢 marmor 解决这个问题的方法。我为自己的项目对其进行了一些修改。无论列数或行数如何,我都使用它来过滤掉表格布局的所有文本视图。这是代码:

      TableLayout tableLayout = getView().findViewById(R.id.tableStats);
      ArrayList<TextView> textViews = new ArrayList<>();
      for(int i = 0; i < tableLayout.getChildCount(); i++){
          TableRow tableRow = (TableRow) tableLayout.getChildAt(i);
          for(int j = 0; j < tableRow.getChildCount(); j++){
              View tempView = tableRow.getChildAt(j);
              if(tempView instanceof TextView){
                  textViews.add((TextView) tempView);
              }
          }
      }
      

      【讨论】:

        【解决方案3】:

        假设每行的列数相同, 这个简单的方法应该可以解决问题:

        private View getCellAtPos(TableLayout table, int pos) {
            TableRow row = (TableRow) table.getChildAt(pos / NUMBER_OF_COLUMNS);
            return row.getChildAt(pos % NUMBER_OF_COLUMNS);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-07-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-30
          • 2011-09-12
          • 1970-01-01
          • 2011-03-18
          相关资源
          最近更新 更多