How to access views inside TableLayout

你离开我真会死。 提交于 2020-01-12 18:49:11

问题


In TableLayout there are 9 Buttons in a 3x3 format. How to access the text on these buttons programatically using the id of TableLayout (not Button Id) ?


回答1:


Use something like,

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 format: (Code for understanding actual may be different)

for(int i=0;i<3;i++)
{
 TableRow row = (TableRow)tblLayout.getChildAt(i);
  for(int j=0;j<3;j++){
    Button button = (Button)row.getChildAt(j); // get child index on particular row
    String buttonText = button.getText().toString();
    Log.i("Button index: "+(i+j), buttonText);
 }
}



回答2:


What you can do is find the instance of TableLayout using

TableLayout layout_tbl = (TableLayout) findViewById(R.id.layout_tbl);

then by using getChildCount() you can iterate through each child of TableLayout and TableRow, also better to check View by using instanceof so that you don't get any 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();
                }
       }
   }


来源:https://stackoverflow.com/questions/11504718/how-to-access-views-inside-tablelayout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!