代码之家  ›  专栏  ›  技术社区  ›  FrinkTheBrave

如何在代码中引用TableLayout单元格

  •  2
  • FrinkTheBrave  · 技术社区  · 14 年前

        <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>
    

    -弗林克

    3 回复  |  直到 14 年前
        1
  •  5
  •   Rich Schuler    14 年前

    你可以用 ViewGroup#getChildAt ViewGroup#getChildCount getChildAt 在你的根上 TableLayout TableRow 表格行 s将允许您访问 TextView

        2
  •  1
  •   SvG    6 年前

    我喜欢马尔默解决这个问题的方法。我为自己的项目做了一些修改。我用它过滤掉一个tablelayout的所有textview,而不考虑列或行的数量。代码如下:

    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
  •  0
  •   marmor    11 年前

    假设每行的列数相同, 这个简单的方法应该可以做到:

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