Android 如何在代码中引用TableLayout单元格
我在xml中定义了一个TableLayout,它有三列四行和一个标题行。 每列包含一个TextViewAndroid 如何在代码中引用TableLayout单元格,android,Android,我在xml中定义了一个TableLayout,它有三列四行和一个标题行。 每列包含一个TextView <TableLayout android:id="@+id/inventory" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="*" <TableRow> <Te
<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>
您可以使用和<根目录上的code>getChildAt
TableLayout将允许您获取TableRow
s,然后在TableRow
s上调用它将允许您访问TextView
s。假设每行的列数相同,
这个简单的方法应该可以做到:
private View getCellAtPos(TableLayout table, int pos) {
TableRow row = (TableRow) table.getChildAt(pos / NUMBER_OF_COLUMNS);
return row.getChildAt(pos % NUMBER_OF_COLUMNS);
}
我喜欢马尔默解决这个问题的方法。我为自己的项目做了一些修改。我使用它过滤掉一个tablelayout的所有文本视图,而不考虑列数或行数。代码如下:
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);
}
}
}
TableLayout TableLayout=getView().findviewbyd(R.id.tableStats);
ArrayList textViews=新建ArrayList();
对于(int i=0;i