我尝试使用此方法避免向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
选择片段时,navigationDrawerMenu
为true
,在片段内选择片段时(从MainFragmentCategory
移至DetialFragmentCategory
)或点击{ {1}}中的{1}}。
profilePhoto
总是navigationDrawer
,为什么会这样?即使我在fragmentPopped
中点击false
并再次profilePhoto
。它应该避免将它添加到backStack第二次(以及第三次和第四次......),但它没有。
任何想法我怎样才能做对吗?
答案 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;