我正在尝试使用此方法避免向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 addToBackStack
是false
当片段从choosen navigationDrawerMenu
并且true
当片段内choosen(从移动MainFragmentCategory
到DetialFragmentCategory
),或者点击profilePhoto
在navigationDrawer
.
fragmentPopped
总是false
,为什么会这样?即使我profilePhoto
再次点击profilePhoto
进入navigationDrawer
.它应该避免将它添加到backStack第二(以及第三和第四......)时间,但事实并非如此.
知道我怎么能做对吗?
您可以在替换片段之前添加以下代码.
// 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;