嵌套片段onbackpresssed转到MainActivity而不是back片段

时间:2018-03-27 22:14:13

标签: android fragment

我从Activity移动到FagmentA然后从FragmentA移动到FragmentB。当停留在FragmentB中时按回按钮它会转到MainActivity(它应该移动到一个Back片段,它是FragmentA)。 怎么了?

从Activity转移到FragmentA

   Fragment fragment = new FragmentA() ;
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
            fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
                    android.R.anim.fade_out);
            fragmentTransaction.replace(R.id.frame, fragment, CURRENT_TAG);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commitAllowingStateLoss();

将FramgentA移至FragmentB

 layout.removeAllViewsInLayout();
            Fragment fragment =new FragmentB ;
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.frame, fragment);
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.commit();

Onbackpressed MainActivity

 @Override
public void onBackPressed() {
    android.app.FragmentManager fm = getFragmentManager();
    if(fm.getBackStackEntryCount()>0){
        fm.popBackStack();
    }else{
        super.onBackPressed(); 
    }

1 个答案:

答案 0 :(得分:1)

您的问题在于导入的FragmentManager使用了两者:

android.support.v4.app.FragmentManagerandroid.app.FragmentManager

改变这个:

@Override
public void onBackPressed() {
    android.app.FragmentManager fm = getFragmentManager();
    if(fm.getBackStackEntryCount()>0){
        fm.popBackStack();
    }else{
        super.onBackPressed(); 
    }

为:

@Override
public void onBackPressed() {
    FragmentManager fm = getSupportFragmentManager();
    if(fm.getBackStackEntryCount()>0){
        fm.popBackStack();
    }else{
        super.onBackPressed(); 
    }

您只需使用支持Fragment添加FragmentManager,这意味着您的现有代码将始终返回0 - > fm.getBackStackEntryCount()直到您使用正确的支持FragmentManager