-1

In default, when the drawer is showing and you press the BackButton it automatically close. but I want when it's showing and user clicks on BackButton, close the app. I tried these solution but didn't work :

Navigation drawer, handling the back button to go to previous fragments

Backbutton press from android navigation drawer

Community
  • 1
  • 1
Ali Aqa
  • 31
  • 1
  • 7

2 Answers2

0

First override back pressed of your activity and then can check if drawer is open

mDrawerLayout.isDrawerOpen(GravityCompat.START);

If this return true simply close your app.

Important : Check your drawer gravity.

Try registering you fragment to back pressed like this:

public void registerBackButton()
{
    if (getView() != null)
    {
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        final BaseFragment frag = this;
        getView().setOnKeyListener(new OnKeyListener()
        {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if (event.getAction() != KeyEvent.ACTION_DOWN)
                {
                    if (keyCode == KeyEvent.KEYCODE_BACK)
                    {
                        if (isVisible())
                        {
                            return frag.onFragmentBackPressed();
                        }
                    }
                }

                return false;
            }
        });
    }
}

Now in onFragmentBackPressed check if drawer is opened or not as mentioned above.

Nauman Afzaal
  • 1,046
  • 12
  • 20
0

onBackPressed will not be called on drawer open or lets say if your keyboard is open then also your back key changes to down arrow. So when you press that down key your keyboard hides and your onBackPressed will not be called still.

Your app will be closed when you press the back button again. Same is the case with keyboard.

So first close the drawer, then press back button again, and then your app will finish

Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66