Search code examples
androidandroid-fragmentsonbackpressed

Using the back button from a fragment in Android


I'm aiming for the following behavior.

When I am on my main activity, If I navigate into fragment 1, and from there, navigate into fragment 2, then when I hit the phone's back button, because I am on fragment 2 I am returned to the home screen, and not fragment 1.

If I had a separate button on the page, this behavior would be very easy, as I could just do:

Button.setOnClickListener(new OnClickListener() 
{
    @Override
    public void onClick(View v) 
    {
        FragmentManager fm = getFragmentManager();
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }
});

I'm running into difficulties because I need to use the phone's own back button. I've read that the OnButtonPressed() event is only usable by an activity, not a fragment, and moving this kind of logic into the activity is proving difficult!

How can I achieve the behavior I'm after?


Solution

  • Just track the backstackcount and you can do whatever you want on the basis of count :

        @Override
        public void onBackPressed() {
            manageBackStack();
        }
    
        private void manageBackStack() {
            switch (getSupportFragmentManager().getBackStackEntryCount()) {
                case 1:
                    //Do when count is 1
                    break;
                case 2:
                    //Do when count is 2
                    break;
                default:
                    finish();
            }
        }
    

    Hope it will help :)