Android 如何访问TableLayout中的视图

Android 如何访问TableLayout中的视图,android,button,tablelayout,Android,Button,Tablelayout,在TableLayout中,有9个按钮为3x3格式。如何使用TableLayout的id(而不是按钮id)以编程方式访问这些按钮上的文本 TableLayout tblLayout = (TableLayout)findViewById(R.id.tableLayout); TableRow row = (TableRow)tblLayout.getChildAt(0); // Here get row id depending on number of row Button button =

TableLayout
中,有9个
按钮
为3x3格式。如何使用TableLayout的id(而不是按钮id)以编程方式访问这些按钮上的文本

TableLayout tblLayout = (TableLayout)findViewById(R.id.tableLayout);
TableRow row = (TableRow)tblLayout.getChildAt(0); // Here get row id depending on number of row
Button button = (Button)row.getChildAt(XXX); // get child index on particular row
String buttonText = button.getText().toString();
3x3格式:(理解实际情况的代码可能不同)


for(int i=0;i您可以使用

TableLayout layout_tbl = (TableLayout) findViewById(R.id.layout_tbl);
然后通过使用
getChildCount()
可以迭代
TableLayout
TableRow
的每个子级,最好使用
instanceof
检查
视图
,这样就不会得到任何
NPE

for (int i = 0; i < layout_tbl.getChildCount(); i++) {
     View parentRow = layout_tbl.getChildAt(i);
     if(parentRow instanceof TableRow){
                for (int j = 0; j < parentRow.getChildCount(); j++){
                   Button button = (Button ) parentRow.getChildAt(j);
                   if(button instanceof Button){
                      String text = button.getText().toString();
                }
       }
   }
for(int i=0;i
如果
表格行
中有一个
线性布局
,在该
线性布局
中,我有一个
按钮
,我想访问该按钮的文本,你能告诉我解决方案吗。(注意:在一个
表格行中有许多
线性布局
,并且没有一个
按钮具有
id
,因为我在一个布局文件中定义了按钮的布局,并根据需要多次将其包含在内)@Ramswaroop-只需调用递归函数,该函数循环
视图组的所有子视图,如果您发现子视图是
按钮,则停止循环。@user370305假设,如果我的表布局有5个表行,但没有任何按钮,我可以这样做:
TableLayout tblLayout=(TableLayout)findViewById(R.id.TableLayout);
TableRow row=(TableRow)tblLayout.getChildAt(0);//这里根据行数获取行id
String Text=row.getText().toString();
在循环中指定了Button Button=…然后检查:if(Button instanceof Button)。请更正答案。
for (int i = 0; i < layout_tbl.getChildCount(); i++) {
     View parentRow = layout_tbl.getChildAt(i);
     if(parentRow instanceof TableRow){
                for (int j = 0; j < parentRow.getChildCount(); j++){
                   Button button = (Button ) parentRow.getChildAt(j);
                   if(button instanceof Button){
                      String text = button.getText().toString();
                }
       }
   }