By default, when onSaveInstanceState
method of an activity is called, it also goes through the view hierarchy and try to save the state of any view if possible and restore those views state if onRestoreInstanceState
method of activity is called later. When each View is called to save the state, we can see this method in the View class:
protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
if (mID != NO_ID && (mViewFlags & SAVE_DISABLED_MASK) == 0) {
mPrivateFlags &= ~PFLAG_SAVE_STATE_CALLED;
Parcelable state = onSaveInstanceState();
if ((mPrivateFlags & PFLAG_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);
}
}
}
EditText inherits from TextView, when check the code of TextView we see the onSaveInstanceState
method return current text and onRestoreInstanceState
method get back the text and display.
Now, back to your code. You save the text content yourself and restore it when onCreate
is called, but EditText itself also save the text and restore when onRestoreInstanceState
method of Activity is call, which is called after onCreate
for sure, one more thing, all your EditText have same id, so when the state of view hierarchy is saved in to a SparseArray, the last EditText state (in this case is text content) will overwrite all the previous. And that's why your problem happen.
Solutions:
- You can override method
onRestoreInstanceState
of activity and not call super method so that you can prevent the views to auto-restore its state, but I don't think this is good idea since there might be other things need to be restored by default, not only your EditText - You can set the attribute saveEnabled of EditText to false so that it will not restore the state itself, I recommend this.