I'm having trouble with restoring state of a View
inside a ViewPager
. The content of the ViewPager
is a view extending FrameLayout
.
The problem is the FrameLayout.onRestoreInstanceState()
is not being called if added programmatically into the ViewPager
Here's the code of my Activity.java
private ViewPager vPager;
private MainPagerAdapter mAdapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
setContentView(R.layout.activity_layout);
// all the findViewById stuff
CustomView cv1 = new CustomView(this);
CustomView cv2 = new CustomView(this);
cv1.setId(R.id.custom_view_id_1);
cv2.setId(R.id.custom_view_id_2);
mAdapter = MainPagerAdapter();
mAdapter.addView(cv1);
mAdapter.addView(cv2);
vPager.setAdapter(mAdapter);
}
MainPagerAdapter
is a class from the accepted answer of this question
Source code for CustomView.java
@Override
protected Parcelable onSaveInstanceState() {
Log.d(TAG, "onSaveInstanceState() called");
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
Log.d(TAG, "onRestoreInstanceState() called");
}
Here's my findings so far:
onSaveInstanceState()
will be called butonRestoreInstanceState()
is not- When I tried to add the View directly to the root of the Activity, it calls both functions.
- I found out that Activity's onRestoreState function will be called before the
ViewPager
calls the adapter'sinstantiateItem()
function. So when the activity restore its state, theViewPager
doesn't have any children yet, thus the savedState doesn't belong to anyone
So I figure out that I need to make one of two things to work:
- Make sure the
ViewPager
instantiate the item before trying to restore the state, or - Calls the CustomView's
onRestoreInstanceState()
manually.
I somehow managed to make option number 2, but is there any way to do option number 1?