How to properly handle screen rotation with a ViewPager and nested fragments?

前端 未结 6 677
执念已碎
执念已碎 2021-01-31 03:42

I\'ve got this activity, which holds a fragment. This fragment layout consists of a view pager with several fragments (two, actually).

When the view pager is created, it

6条回答
  •  隐瞒了意图╮
    2021-01-31 04:06

    I had the same issue - I assume you're subclassing FragmentPagerAdapter for your pager adapter (as getItem() is specific to FragmentPagerAdapter).

    My solution was to instead subclass PagerAdapter and handle the fragment creation/deletion yourself (reimplementing some of the FragmentPagerAdapter code):

    public class ListPagerAdapter extends PagerAdapter {
        FragmentManager fragmentManager;
        Fragment[] fragments;
    
        public ListPagerAdapter(FragmentManager fm){
            fragmentManager = fm;
            fragments = new Fragment[5];
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            assert(0 <= position && position < fragments.length);
            FragmentTransaction trans = fragmentManager.beginTransaction();
            trans.remove(fragments[position]);
            trans.commit();
            fragments[position] = null;
    }
    
        @Override
        public Fragment instantiateItem(ViewGroup container, int position){
            Fragment fragment = getItem(position);
            FragmentTransaction trans = fragmentManager.beginTransaction();
            trans.add(container.getId(),fragment,"fragment:"+position);
            trans.commit();
            return fragment;
        }
    
        @Override
        public int getCount() {
            return fragments.length;
        }
    
        @Override
        public boolean isViewFromObject(View view, Object fragment) {
            return ((Fragment) fragment).getView() == view;
        }
    
        public Fragment getItem(int position){
            assert(0 <= position && position < fragments.length);
            if(fragments[position] == null){
                fragments[position] = ; //make your fragment here
            }
            return fragments[position];
        }
    }
    

    Hope this helps.

提交回复
热议问题