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

前端 未结 6 729
执念已碎
执念已碎 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 03:58

    My answer is kind of similar to Joshua Hunt's one, but by commiting the transaction in finishUpdate method you get much better performance. One transaction instead of two per update. Here is the code:

    private class SuchPagerAdapter extends PagerAdapter{
    
        private final FragmentManager mFragmentManager;
        private SparseArray mFragments;
        private FragmentTransaction mCurTransaction;
    
        private SuchPagerAdapter(FragmentManager fragmentManager) {
            mFragmentManager = fragmentManager;
            mFragments = new SparseArray<>();
        }
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment fragment = getItem(position);
            if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
            mCurTransaction.add(container.getId(),fragment,"fragment:"+position);
            return fragment;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (mCurTransaction == null) {
                mCurTransaction = mFragmentManager.beginTransaction();
            }
            mCurTransaction.detach(mFragments.get(position));
            mFragments.remove(position);
        }
    
        @Override
        public boolean isViewFromObject(View view, Object fragment) {
            return ((Fragment) fragment).getView() == view;
        }
    
        public Fragment getItem(int position) {         
            return YoursVeryFragment.instantiate();
        }
    
        @Override
        public void finishUpdate(ViewGroup container) {
            if (mCurTransaction != null) {
                mCurTransaction.commitAllowingStateLoss();
                mCurTransaction = null;
                mFragmentManager.executePendingTransactions();
            }
        }
    
    
        @Override
        public int getCount() {
            return countOfPages;
        }
    
    }
    

提交回复
热议问题