Android FragmentStatePagerAdapter

后端 未结 5 1331
太阳男子
太阳男子 2021-02-01 18:02

I\'m working with a FragmentStatePagerAdapter using this example.

The MyAdapter class is implemented as follows:

public static class MyAdapter extends Fr         


        
5条回答
  •  鱼传尺愫
    2021-02-01 18:35

    While @imiric's solution is very concise, it still bothers me that it requires knowledge of the implementation of the class. My solution involves adding the following to your adapter, which should behave nicely with a FragmentStatePagerAdapter possibly destroying fragments:

        private SparseArray> mFragments = new SparseArray<>();
    
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment f = (Fragment) super.instantiateItem(container, position);
            mFragments.put(position, new WeakReference<>(f));  // Remember what fragment was in position
            return f;
        }
    
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            super.destroyItem(container, position, object);
            mFragments.remove(position);
        }
    
        public Fragment getFragment(int position) {
            WeakReference ref = mFragments.get(position);
            Fragment f = ref != null ? ref.get() : null;
            if (f == null) {
                Log.d(TAG, "fragment for " + position + " is null!");
            }
            return f;
        }
    

提交回复
热议问题