Saving Fragment state in ViewPager

前端 未结 6 1400
旧巷少年郎
旧巷少年郎 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:13

    I tripped on some similar ground... I wanted to keep my fragments saved within my adapter to avoid useless reloading since I only had 5 fragments in the FragmentPagerAdapter.

    I basically had to create an array and override the getItem(position) method:

    private StoryListFragment[] fragmentsArray
            = new StoryListFragment[getCount()];
    
    public SectionsAdapter(FragmentManager fm) {
        super(fm);
    }
    
    
    @Override
    public Fragment getItem(int position) {
    
        if(fragmentsArray[position]!=null)
            return fragmentsArray[position];
        StoryListFragment storyListFragment = null;
        switch(position){
            case(0):
                storyListFragment = StoryListFragment.newInstance(StoriesBank.NEWS);
                break;
            case(1):
                storyListFragment = StoryListFragment.newInstance(StoriesBank.FEATURES);
                break;
            case(2):
                 storyListFragment=  StoryListFragment.newInstance(StoriesBank.ARTS);
                break;
        }
    
        fragmentsArray[position] =  storyListFragment;
        return storyListFragment;
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        StoryListFragment fragment = (StoryListFragment) super.instantiateItem(container, position);
        fragmentsArray[position] = fragment;
        return fragment;
    }
    

提交回复
热议问题