我在解决 BackStack 遇到的问题时遇到了麻烦。我有 3 个由 Activity 管理的片段:
我使用此代码的片段之间的导航:
private void showFragment(BabysitFragment babysitFragment, UserRequest userRequest) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
switch (babysitFragment) {
case CHILDREN_OVERVIEW:
toolbar.setVisibility(View.VISIBLE);
Fragment childrenSpecification = ChildrenOverviewFragment.newInstance(userRequest);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.fragment_container, childrenSpecification, BabysitFragment.CHILDREN_OVERVIEW.getSimpleName()).commit();
break;
case CHILD_SPECIFICATION:
toolbar.setVisibility(View.VISIBLE);
Fragment childSpecification = ChildSpecificationFragment.newInstance(userRequest);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.fragment_container, childSpecification, BabysitFragment.CHILD_SPECIFICATION.getSimpleName()).commit();
break;
}
}
//Gets called by FinalizeFrag and ChildSpecificationFrag
@Override
public void onChildrenOverviewNeeded(UserRequest userRequest) {
showFragment(BabysitFragment.CHILDREN_OVERVIEW, userRequest);
}
//Gets called by ChildrenOverviewFrag
@Override
public void onChildSpecificationNeeded(UserRequest userRequest) {
showFragment(BabysitFragment.CHILD_SPECIFICATION, userRequest);
}
我希望用户能够使用其他 2 个片段的后退按钮返回 FinalizeFrag。这适用于当前代码,但在 1 个流程中我确实遇到了问题:
- 用户将新的“孩子”保存在 ChildSpecificationFrag 中(工具栏中的保存图标)
- 用户被重定向到 ChildrenOverviewFrag
- 用户按下返回按钮
- 停留在 ChildrenOverviewFrag 上(应该重定向到 FinalizeFrag)
注意:当我再次按下按钮时,它会重定向到 FinalizeFrag
单击关闭按钮时的代码(ChildSpecificationFragment):
if (id == android.R.id.home) {
getActivity().onBackPressed();
}
单击保存按钮时的代码(ChildSpecificationFragment):
...
userRequest.getFamilyDetails().getChildren().add(child);
getActivity().getSupportFragmentManager().popBackStackImmediate();
onChildrenOverviewNeededListener.onChildrenOverviewNeeded(userRequest, this);
如您所见,我正在从 BackStack 中删除 Fragment。我究竟做错了什么?提前致谢!