y07*_*7k2 6 android android-fragments back-stack android-studio
我正在尝试使用此方法避免向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();
}
}
Run Code Online (Sandbox Code Playgroud)
导航抽屉包含: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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2945 次 |
| 最近记录: |