尝试避免向backStack添加两次相同的片段,popBackStackImmediate总是返回false

时间:2016-07-20 06:58:53

标签: android android-studio android-fragments back-stack

我尝试使用此方法避免向backStack添加相同的片段:

public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, Boolean addToBackStack) {
        String backStateName = fragment.getClass().getName();
        boolean fragmentPopped = fragmentManager.popBackStackImmediate(backStateName, 0);

        if (addToBackStack && !fragmentPopped && fragmentManager.findFragmentByTag(backStateName) == null) {
            fragmentManager
                    .beginTransaction()
//                    .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out)
                    .replace(R.id.container, fragment)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .addToBackStack(backStateName) // was 'backStateName'
                    .commit();
        } else {
            if (!addToBackStack)
                fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
            fragmentManager
                    .beginTransaction()
//                    .setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right, android.R.anim.fade_in, android.R.anim.fade_out)
                    .replace(R.id.container, fragment)
                    .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                    .disallowAddToBackStack()
                    .commit();
        }
    }

导航抽屉包含:带有profilePhoto的ImageView会打开ProfileMainFragment,而少数类别会打开MainFragmentCategory。从Boolean addToBackStackfalse选择片段时,navigationDrawerMenutrue,在片段内选择片段时(从MainFragmentCategory移至DetialFragmentCategory)或点击{ {1}}中的{1}}。

profilePhoto总是navigationDrawer,为什么会这样?即使我在fragmentPopped中点击false并再次profilePhoto。它应该避免将它添加到backStack第二次(以及第三次和第四次......),但它没有。

任何想法我怎样才能做对吗?

1 个答案:

答案 0 :(得分:8)

您可以在替换片段之前添加以下代码。

// Replace fragmentCotainer with your container id
Fragment currentFragment = fragmentManager.findFragmentById(R.id.fragmentCotainer);
// Return if the class are the same
if(currentFragment.getClass().equals(fragment.getClass())) return;