我有四个碎片:A,B,C,D。现在我从A - >移动B所以我的代码将是
从 A到B
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new B())
.addToBackStack("A")
.commit();
现在从 B到C ,所以代码将是
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new C())
.addToBackStack("B")
.commit();
现在从 C到D 。但是我不希望在backstack中包含C,因为在背压时我不希望显示C片段。
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, new D())
.commit();
现在,当我按下返回按钮时,它将完美地工作到A.现在,如果我再次重复相同的过程。现在再次按下From D Fragment,我将直接发送到A片段而不是B片段。你能否弄清楚我在上面代码中所犯的错误?
答案 0 :(得分:1)
您必须为单个Stack提供addToBackStack的相同String值。
.replace(R.id.content_frame, new B())
.addToBackStack("stack")
.replace(R.id.content_frame, new C())
.addToBackStack("stack")
答案 1 :(得分:0)
这是BackStackChangedListener的代码。
public static void performNoBackStackTransaction( final FragmentManager fragmentManager, String tag, Fragment fragment) {
final int newBackStackLength = fragmentManager.getBackStackEntryCount() +1;
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment, tag)
.addToBackStack(tag)
.commit();
fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
int nowCount = fragmentManager.getBackStackEntryCount();
if (newBackStackLength != nowCount) {
// we don't really care if going back or forward. we already performed the logic here.
fragmentManager.removeOnBackStackChangedListener(this);
if ( newBackStackLength > nowCount ) { // user pressed back
fragmentManager.popBackStackImmediate();
}
}
}
});
}