How to access views inside TableLayout
Asked Answered
O

2

7

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

Ovoid answered 16/7, 2012 at 12:52 Comment(0)
S
20

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);
 }
}
Stupe answered 16/7, 2012 at 12:54 Comment(3)
Can you tell me solution if the TableRow has a LinearLayout inside it and inside that LinearLayout i have my Button whose text i want to access. (NOTE: There are many LinearLayout inside one TableRow and none of the Button have ids as i have defined the layout for buttons in one layout file and included it as many times i need it)Gaikwar
@Ramswaroop - Just call recursive function which loop all child of ViewGroup and if you found child view as a Button stop the loop.Stupe
@Stupe hypothetically, if I had a table layout with 5 table rows without any buttons, can I do this: TableLayout tblLayout = (TableLayout)findViewById(R.id.tableLayout); TableRow row = (TableRow)tblLayout.getChildAt(0); // Here get row id depending on number of row String Text = row.getText().toString();Breathing
T
6

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();
                }
       }
   }
To answered 16/7, 2012 at 13:18 Comment(1)
In a loop you assigned Button button = ... And after that check: if (button instanceof Button). Please, correct an answer.Wreckfish

© 2022 - 2024 — McMap. All rights reserved.