开发者

How to refer to TableLayout cells in code

开发者 https://www.devze.com 2023-01-13 00:53 出处:网络
I have a TableLayout defined in my xml with three columns and four rows plus a heading row. Each column contains a TextView.

I have a TableLayout defined in my xml with three columns and four rows plus a heading row. Each column contains a 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>
    <Table开发者_JAVA百科Row>
        <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>

Is there any way of referring to the TextViews in code, without having to id them individually. I was thinking there might be come way of getting row/col views from the tableview.

-Frink


You can use ViewGroup#getChildAt and ViewGroup#getChildCount. getChildAt on your root TableLayout will allow you to get the TableRows and subsequently calling it on the TableRows will allow you to access the TextViews.


I liked marmor's way of solving this. I modified it somewhat for my own project. I use it to filter out all the textviews of a tablelayout regardless of the number of columns or rows. Here is the code:

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);
        }
    }
}


Assuming you have the same number of columns for each row, this simple method should do the trick:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号