Search code examples
android-fragmentsback

back button press handling in fragments


I am developing an application which is using Navigation drawer, so I have to use fragments to navigate using the drawer. My problem is I'm in a particular fragment, and when I press hardware back button in the phone it should exit the application. I have implemented it as below.

rootView.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View arg0, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK){

                if(getFragmentManager().getBackStackEntryCount()>0){

                    getActivity().finishAffinity();

                    //return true;
                }
                else{
                    getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);


                }
            /*  getActivity().finishAffinity();
                getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
                */
                return true;
              }
            else{
            return false;
            }
        }
    });

here i can successfully exit from the app, but when I launch the app again by clicking the icon, it checks if the user is already logged in to the app and if already logged in, redirects to the fragment where I previously was. When I press the back button again it doesn't exit the app... it goes to the login activity... How can I overcome this problem?


Solution

  • I'm quite late at this. But in case you haven't figured this out, the best bet you have here is to architect your application such that the back-button press event gets propagated from active fragment down to host Activity. So, it's like.. if one of the active fragments consume the back-press, the Activity wouldn't get to act upon it, and vice-versa.

    One way to do it is to have all your Fragments extend a base fragment that has an abstract 'boolean onBackPressed()' method.

    Keep track of active fragment inside your Activity and inside it's onBackPressed callback write something like this

    @Override
    public void onBackPressed() {
       if(!activeFragment.onBackPressed())
          super.onBackPressed();
       }
    }
    

    This post has this pattern described in detail