Saving Fragment state in ViewPager

前端 未结 6 1382
旧巷少年郎
旧巷少年郎 2020-12-04 15:25

I tried out the sample code from the API and it didn\'t really work so I implemented my own:

FragmentPagerSupport

public class Fragm         


        
6条回答
  •  温柔的废话
    2020-12-04 16:30

    The adapter should be extended from FragmentStatePagerAdapter instead of FragmentPageAdapter and the adapter will keep reference from position to fragment item. On the activity or fragment parent, set listener OnPageChangeListener for PageIndicator to detect the position of fragment item has been activated and update related data's state.

    About the data state of fragment item, I think should save/restore state from Activity or Fragement parent.

    The adapter can add some code as following:

    public static class MyAdapter extends FragmentStatePagerAdapter {
        private SparseArray mPageReferenceMap 
                                  = new SparseArray();
        ...
    
        @Override 
        public Object instantiateItem(ViewGroup viewGroup, int position) {
            Object obj = super.instantiateItem(viewGroup, position);
    
            //Add the reference when fragment has been create or restore
            if (obj instanceof TestFragment) {
                    TestFragment f= (TestFragment)obj;
                    mPageReferenceMap.put(position, f);
            }
    
            return obj;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //Remove the reference when destroy it
            mPageReferenceMap.remove(position);
    
            super.destroyItem(container, position, object);
        }
    
        public TestFragment getFragment(int key) {
    
            return mPageReferenceMap.get(key);
        }
        ...
    }
    

    Hope this help.

提交回复
热议问题