Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to restore state of an Android View (UI)?
    text
    copied!<p>I'm trying to save state of my view in one activity and pass it to another activity using a Bundle. In the second activity I try to restore the view state using the bundle. </p> <p>First Activity</p> <pre><code>private View CreateView() { ScrollView scrollView = new ScrollView(this); final LinearLayout layout = new LinearLayout(this); layout.setOrientation(android.widget.LinearLayout.VERTICAL); scrollView.addView(layout); Button btn = new Button(this); btn.setId(100); btn.setText("Button Text"); btn.setOnClickListener(new ClickListener()); layout.addView(btn); return scrollView; } </code></pre> <p>onCreate</p> <pre><code>super.onCreate(savedInstanceState); View v = CreateView(); setContentView(v); </code></pre> <p>Saving state</p> <pre><code>SparseArray&lt;Parcelable&gt; array = new SparseArray&lt;Parcelable&gt;(); view.saveHierarchyState(array); Bundle bundle = new Bundle(); bundle.putSparseParcelableArray("state", array); Intent intent = new Intent(context, SecondActivity.class); intent.putExtras(bundle); startActivity(intent); </code></pre> <p>Second Activity onCreate</p> <pre><code>bundle = this.getIntent().getExtras(); View view = new View(this); view.restoreHierarchyState(bundle.getSparseParcelableArray("state")); setContentView(view.getRootView()); Button btn = (Button)findViewById(100); </code></pre> <p>Everything works without an exception. However, I face two issues: 1. The view in second activity is blank. Though I've restored the saved state I can't see anything 2. Instance for the button (with id 100) in second activity is always null</p> <p>While debugging I can see one of the values in the bundle having an id 100</p> <p>Any help on what I seem to be doing wrong will be appreciated. Thanks</p>
 

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