FragmentPagerAdapter is not removing items (Fragments) correctly

前端 未结 9 1217
别跟我提以往
别跟我提以往 2021-01-30 01:30

I have implemented the FragmentPagerAdapter and and using a List to hold all fragments for my ViewPager to display. On

9条回答
  •  庸人自扰
    2021-01-30 02:10

    Taking "the best of both worlds" (I mean the answers by @Tericky Shih and @mikepenz) we have it short and simple:

    public class MyPagerAdapter extends FragmentPagerAdapter {
    
        public ArrayList fragments = new ArrayList();    
    
        ...
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            if (position >= getCount()) fm.beginTransaction().remove((Fragment) object).commit();
        }
    
        @Override
        public int getItemPosition(Object object) {
            if (fragments.contains(object)) return fragments.indexOf(object);
            else return POSITION_NONE;
        }
    }
    

    The main difference is that if some fragment is not changed you don't have to destroy its view and don't have to return POSITION_NONE for it. At the same time, I've encountered a situation when ViewPager was holding a reference to an item which was already destroyed, therefore the check if (fragments.contains(object)) helps to determine if that item is not needed anymore.

提交回复
热议问题