FragmentTransaction : replace and addToBackStack not working together?

后端 未结 2 1543
暖寄归人
暖寄归人 2020-12-25 08:35

I\'m fairly new to Android development and now running in to weird behaviour.

  • I have an empty FrameLayout to be the container of a fragment.
  • If user p
2条回答
  •  抹茶落季
    2020-12-25 09:16

    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

提交回复
热议问题