I am working with CustomView which extends some Android view like FrameLayout. In my layout I use a ViewPager with a custom PagerAdapter.
The problem is that my
The easy answer : it's because I was not setting id to my view (custom or not). Android didn't manage the onSaveInstanceState/onRestoreInstanceState
if no id is set to the view.
So as my customView was extending base View, with not extra property, setting an ID to the view solved the issue and so onSaveInstanceState/onRestoreInstanceState are called as it should.
So to summary, use one of this approach :
from XML
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
android:id="@+id/scrollView">
</ScrollView>
OR from Java
yourCustomView.setId(R.id.myCustomView);
is last case, you add static id to res/values/ids.xml <item name="myCustomView" type="id"/>
Saving State by Default
We now have everything in place for our view to save and restore its state. However, this will not happen by default. If you want instances of your view to save state automatically, you can add this line to the init method:
setSaveEnabled(true);
Whether or not to do this is up to you. Even if your view does not save state by default, users of the view can always enable saving state by calling setSaveEnabled(true)
, or by specifying android:saveEnabled=“true”
in the layout xml.