Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View onSaveInstanceState not called

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 View did not restore it's state when the fragment is re-attached to the ViewPager/Activity. For example, I have three fragments, if I swipe to the last one and come back to the first, the ScrollView is not where I let it : it's back to default, on top.

I know that with a PagerAdapter, not all fragment are active on the same time, basically juste the +1/-1.

I can't find why my View.onSaveInstanceState() is not called, so as onRestoreInstanceState.

like image 691
Hugo Gresse Avatar asked Feb 18 '15 14:02

Hugo Gresse


1 Answers

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"/>

like image 92
Hugo Gresse Avatar answered Sep 19 '22 00:09

Hugo Gresse