Why is the Destroy method in fragments in ViewPager on the leaf?



  • I have a fragment, and inside it, I'm causing three fragments with the help of the tab, When I switch between first and second, everything's fine and fragments aren't destroyed, but when I switch from second to third, then the first fragment dies and the Destroy method is released.

    Can anyone explain what the problem is, or is it worthwhile?

    public class PagerAdapter extends FragmentStatePagerAdapter {
    
        private static final int NUM_PAGES=3;
        private Context mContext;
    
    public PagerAdapter(FragmentManager fm,Context mContext) {
        super(fm);
        this.mContext=mContext;
    }
    
    @Override
    public Fragment getItem(int position) {
    
        switch(position){
            case 0 :
                AnimalsFragment animalsFragment = new AnimalsFragment();
                return animalsFragment;
            case 1:
                BirdsFragment birdsFragment = new BirdsFragment();
                return birdsFragment;
            case 2:
                InsectsFragment insectsFragment = new InsectsFragment();
                return insectsFragment;
            default:
                return null;
        }
    }
    
    //Total num of fragments
    @Override
    public int getCount() {
        return NUM_PAGES;
    }
    
    //Return page title depending on position
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            case 0:
                return mContext.getString(R.string.animals) ;
            case 1:
                return mContext.getString(R.string.birds) ;
            case 2:
                return mContext.getString(R.string.insects) ;
    
        }
        return null;
    }
    



  • It's happening as it should be. ViewPager Maintains only the current, visible fragments + fragments on the left and right of the current. That's three. Only two fragments are stored in the memory of the first and last fragments.

    Modify this default behaviour by method ViewPager.setOffscreenPageLimit(int pageLimit)♪ In the case of three fragments, the number should be transferred 2 in the method:

    viewPager.setOffscreenPageLimit(2);
    //теперь при переключении меж фрагментами будут сохраняться помимо отображаемого по два фрагмента слева и стправа от текущего, т.е. все 3 в любом случае.
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2