FragmentTransaction : replace and addToBackStack not working together?

匆匆过客 提交于 2019-11-30 00:49:36

addToBackstack creates a snapshot of your fragments state. Which means when you press the back button, you are actually reverting to the last state that addToBackstack was called on.

In your case, you add a Fragment. The back button would remove this added fragment. When you call replace, and add to backstack again, you now have two states on the backstack (1. when you had the first fragment added, 2. when you had no fragments added). If you the back button to remove the current fragment, the don't use addToBackstack. Only use addToBackstack when you want to preserve the state of fragments in a view.

For those, who are still looking for solution.

In the main Activity class (which is hosting the fragments)just override onBackPressed().

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

There is no onBackPressed() method in fragment, and this method is just for the activity. So,when we press the back key, the default behaviour of activity is shown, which is

you will either go to previous activity(if there is any) or the app will exit.

Now we need to override this method to tell the activity that when we press the back key, if there are any fragments in back stack, pop them out (and this is when the addToBackStack() comes into picture). Otherwise follow the default behaviour.

find more details here here

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