Index 2?


In Listing 24.9 (p. 395 in print), the for-loop initializes i to 2 and you explain that it is to skip the two text views. Is there another way to do this to avoid hardcoding in the constant? If you change the layout, you would have to remember to change the constant. It could easily lead to a bug.


Yes there is. If you cast the tableLayout.getChildAt(x) to a View instead of a TableRow then you can use instanceof to see if it truly is a TableRow. If it is, cast it as such and proceed to setup the buttons, if not skip it. In addition, I am skipping the final row of buttons (Ultimately the delete, zero and Enter) by doing this: i <= tableLayout.getChildCount()-2 - the reason is that you are actually assigning those buttons the values of 10, 11 and 12 only to replace them with the values “Delete”, “0” and “Enter” so why not just skip them in the “for i” loop to begin with.

TableLayout tableLayout = (TableLayout)view.findViewById(;
int number = 1;
for (int i =0; i <= tableLayout.getChildCount()-2; i++){
View viewControl = (View) tableLayout.getChildAt(i);
if (viewControl instanceof TableRow){
TableRow tableRow = (TableRow)viewControl;
for (int j = 0; j < tableRow.getChildCount(); j++){
Button button = (Button)tableRow.getChildAt(j);
button.setText("" + number);