Android Fragment清除FragmentPagerAdapter中的后台堆栈

时间:2017-11-07 12:13:58

标签: android android-fragments fragmentpageradapter fragment-backstack

我正在使用FragmentPagerAdapter有三个标签,每个标签都有自己的根片段(每个标签都有自己的FrameLayout)。这个根Fragment用作其他Fragments的占位符。我想要实现的是每当切换选项卡时Fragment应该清除返回堆栈。 这是adapter代码。

@Override
    public Fragment getItem(int position) {
        MainScreen mActivity = (MainScreen)mContext;
        FragmentManager manager = mActivity.getSupportFragmentManager();
        if (manager.getBackStackEntryCount() > 0) {
            FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
            manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }

        switch (position) {
            case 0:
                return new BaseFragment();
            case 1:
                return new BaseActivityFragment();
            case 2:
                return new BaseSalesFragment();
            default:
                return null;
        }
    }

1 个答案:

答案 0 :(得分:1)

感谢参与。这样做了。

pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            FragmentManager manager = mActivity.getSupportFragmentManager();
            if (manager.getBackStackEntryCount() > 0) {
                while (manager.getBackStackEntryCount() > 0){
                    manager.popBackStackImmediate();
                }
            }

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });