Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager inside Fragment doesn't restore child fragments' state

I hav a problem. I have a fragment, which contains viewpager inside. For viewpager i use FragmentPagerAdapter extension. There are recycler views inside of each pager fragment. The question is that i can't restore scroll position after screen rotation inside recycler views of viewpager. I thought that problem is in recyclerview, but soon i found out that after screen rotation fragments inside viewpager are being recreating, so onCreate() and onDestroy() are called, even though they shouldn't. I also tried use onSaveInstanceState(bundle) and found out that inside onCreateView() this bundle is always null. So what should i do? This topic didn't help me.

like image 703
Geron Thunder Avatar asked Oct 18 '22 23:10

Geron Thunder


1 Answers

Well, i have found an answer. The problem is in me). There is hierarchy : MainActivity with frame layout for fragment - PagerFragment which contains viewpager - fagments inside viewpager. The problem is that after screen rotation inside of activity i was allways replacing PagerFragment, such as:

android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragment = new PagerFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();

but i should do this:

Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (fragment == null) {
        android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragment = new PagerFragment();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
}

It was completely my fault and i am ashamed. I am sorry.

like image 124
Geron Thunder Avatar answered Nov 15 '22 06:11

Geron Thunder