Pressing back does not return to previous fragment

我怕爱的太早我们不能终老 提交于 2019-12-05 04:50:43

Your code is a mixup, you use ActionBarActivity from appcompat and not using getSupportFragmentManager() and the fragments import should be the appcompat one if you decide to use it. If not, use Activity instead of ActionBarActivity and the simple Fragment import with FragmentManager

Add this to your activity android:configChanges="keyboardHidden|orientation|screenSize" This will stop your activity from restarting when you rotate. use setRetainInstance(true) on fragments.

In your Activity overwrite:

@Override
public void onBackPressed() {
    if (getFragmentManager().getBackStackEntryCount() > 0) {
        getFragmentManager().popBackStack();
    } else {
        super.onBackPressed();
    }
}

And probably you need to use in every commited fragment transaction:

FragmentTransaction.addToBackStack(null);

You are not adding the MainMenuFragment to the back stack. You can try this one on your activity:

getFragmentManager().beginTransaction().add(
R.id.frag_container, new MainMenuFragment()).
addToBackStack(null).commit();

When you add or replace a fragment with the FragmentManager, you need to manually add the old fragment to the backstack with addToBackStack() before calling commit().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!