点按“返回”按钮后片段消失

时间:2015-05-21 10:29:39

标签: android android-fragments

我有两个片段 - FragmentAFragmentB

我尝试从FragmentB显示FragmentA

    FragmentB fragmentB = new FragmentB();

    MainActivity activity = (MainActivity) getActivity();
    int fragmentContainer = activity.getFragmentContainer();

    FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(fragmentContainer, fragmentB);
    fragmentTransaction.addToBackStack(null);

    fragmentTransaction.commit();

MainActivity

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        fragmentA = new FragmentA(getSupportFragmentManager());
        //...

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(FRAGMENT_CONTAINER,fragmentA);
        fragmentTransaction.commit();
    }

FragmentB显示,但是当我点击后退按钮时我有下一个情况 - FragmentB被解雇,但FragmentA没有显示。

为什么会发生这种情况以及需要编辑才能获得正确的结果?

2 个答案:

答案 0 :(得分:0)

getActivity().getChildFragmentManager().beginTransaction();

使用它可能在fragmentB

中起作用

答案 1 :(得分:0)

感谢New Developer提供的link

我们需要的只是添加一个

@Override
public void onBackPressed(){
  if (getSupportFragmentManager().getBackStackEntryCount() == 1){
    finish();
  }
  else {
    super.onBackPressed();
  }
}

private void replaceFragment (Fragment fragment){
  String backStateName =  fragment.getClass().getName();
  String fragmentTag = backStateName;

  FragmentManager manager = getSupportFragmentManager();
  boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

  if (!fragmentPopped && manager.findFragmentByTag(fragmentTag) == null){ //fragment not in back stack, create it.
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content_frame, fragment, fragmentTag);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.addToBackStack(backStateName);
    ft.commit();
  } 
}

并管理活动中的片段。

因此,如果我们需要一个交换片段,只需调用:

replaceFragment(new MySwappingFragment());