How to access views in TableLayout

There are 9 Buttons in TableLayout in 3x3 format. How to access the text on these buttons programmatically using the TableLayout identifier (not the button identifier)?

+7
source share
2 answers

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: (The code for understanding the actual may vary)

 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); } } 
+19
source

What you can do is find an instance of TableLayout using

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

then with getChildCount() you can TableLayout over each child of TableLayout and TableRow , it is also better to check View with 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(); } } } 
+6
source

All Articles