I am attempting to save and restore a view hierarchy consisting of a table of buttons. The number of table rows and buttons required in the table is not known until runtime
If it works with Views with an ID, why not give each button an ID in the table when you are creating them? See if that works.
How can I assign an ID to a view programmatically?
After searching through the source code for Activity
, View
and ViewGroup
, I learned that the programmatically added views must be programmatically added and assigned the same ID each time onCreate(Bundle)
is called. This is true regardless of whether it is creating the view for the first time, or recreating the view after destroying the activity. The saved instance state of the programmatically added views is then restored during the call to Activity.onRestoreInstanceState(Bundle)
. The easiest answer to the code above is simply to remove the check for savedInstanceState == null
.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup this activity's view.
setContentView(R.layout.game_board);
TableLayout table = (TableLayout) findViewById(R.id.table);
int gridSize = 5;
// Create the table elements and add to the table.
int uniqueId = 1;
for (int i = 0; i < gridSize; i++) {
// Create table rows.
TableRow row = new TableRow(this);
row.setId(uniqueId++);
for (int j = 0; j < gridSize; j++) {
// Create buttons.
Button button = new Button(this);
button.setId(uniqueId++);
row.addView(button);
}
// Add row to the table.
table.addView(row);
}
}
This line recreates an empty layout:
setContentView(R.layout.game_board);
Besides, you assign equal id's to rows and buttons. You should have used one counter for both the rows and buttons:
int idCounter = 1;
for (int i = 0; i < gridSize; i++) {
TableRow row = new TableRow(this);
row.setId(idCounter++);
for (int j = 0; j < gridSize; j++) {
Button button = new Button(this);
button.setId(idCounter++);
row.addView(button);
}
...
}