Note that there are some explanatory texts on larger screens.

plurals
  1. PORestoring view hierarchy from saved state does not restore views added programatically
    primarykey
    data
    text
    <p>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, and are added programmatically to an inflated xml layout in my <code>Activity</code>'s <code>onCreate(Bundle)</code> method. My question is: can the final table be saved and restored using Android's default view saving/restoring implementation?</p> <p>An example of my current attempt is below. On the initial run, the table builds as expected. When the activity is destroyed (by rotating the device), the rebuilt view shows only an empty <code>TableLayout</code> with no children.</p> <p>The xml file referenced in <code>setContentView(int)</code> includes, among other things, the empty <code>TableLayout</code> that the buttons are added to.</p> <pre><code>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); // If this is the first time building this view, programmatically // add table rows and buttons. if (savedInstanceState == null) { int gridSize = 5; // Create the table elements and add to the table. int uniqueId = 1; for (int i = 0; i &lt; gridSize; i++) { // Create table rows. TableRow row = new TableRow(this); row.setId(uniqueId++); for (int j = 0; j &lt; gridSize; j++) { // Create buttons. Button button = new Button(this); button.setId(uniqueId++); row.addView(button); } // Add row to the table. table.addView(row); } } } </code></pre> <p>My understanding is that Android saves the state of views as long as they have an ID assigned to them, and restores the views when the activity is recreated, but right now it seems to reinflate the xml layout and nothing more. When debugging the code, I can confirm that <code>onSaveInstanceState()</code> is called on each <code>Button</code> in the table, but <code>onRestoreInstanceState(Parcelable)</code> is not.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload