Remove Fragment Page from ViewPager in Android

前端 未结 17 1418
庸人自扰
庸人自扰 2020-11-22 17:20

I\'m trying to dynamically add and remove Fragments from a ViewPager, adding works without any problems, but removing doesn\'t work as expected.

Everytime I want to

17条回答
  •  广开言路
    2020-11-22 17:45

    I had the idea of simply copy the source code from android.support.v4.app.FragmentPagerAdpater into a custom class named CustumFragmentPagerAdapter. This gave me the chance to modify the instantiateItem(...) so that every time it is called, it removes / destroys the currently attached fragment before it adds the new fragment received from getItem() method.

    Simply modify the instantiateItem(...) in the following way:

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        final long itemId = getItemId(position);
    
        // Do we already have this fragment?
        String name = makeFragmentName(container.getId(), itemId);
        Fragment fragment = mFragmentManager.findFragmentByTag(name);
    
        // remove / destroy current fragment
        if (fragment != null) {
            mCurTransaction.remove(fragment);
        }
    
        // get new fragment and add it
        fragment = getItem(position);
        mCurTransaction.add(container.getId(), fragment,    makeFragmentName(container.getId(), itemId));
    
        if (fragment != mCurrentPrimaryItem) {
            fragment.setMenuVisibility(false);
            fragment.setUserVisibleHint(false);
        }
    
        return fragment;
    }
    

提交回复
热议问题