In my course of creating an android app i’ve encoutered several times the issue of needing to inflate an extra layout or layout into existing layouts that you set with ‘setContentiew()’.
The process is simple, Since i’m usually using LinearLayout as my main layout all i have to do is get the LainearLayout objet using findViewByID(), inflate my new layout and use myLinearLayout.addView(inflaterView);
This does the trick hoever once it comes down to get save and restore for my form’s statefull items(checkboxes\EditText etc…) it doesn’t work. to see why it fails to work, let’s take a look on android’s code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | protected void dispatchSaveInstanceState(SparseArray<parcelable> container) { if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) { mPrivateFlags &= ~SAVE_STATE_CALLED; Parcelable state = onSaveInstanceState(); if ((mPrivateFlags & SAVE_STATE_CALLED) == 0) { throw new IllegalStateException( "Derived class did not call super.onSaveInstanceState()"); } if (state != null) { // Log.i("View", "Freezing #" + Integer.toHexString(mID) // + ": " + state); container.put(mID, state); } } } |
So it’s all pretty simple. If you have an ID then call the View’s onSaveInstanceState() that will create a Parcelable of it’s state and will saved in a SparceArray(integer to Object Mapping that should be more effecient than HashMap) connected to it’s ID. If you have no ID than your data will not be automatically saved.
» Read more: Android layout inflation and ID’s issue.