Search code examples
androidonkeydownonbackpressed

First onBackPressed close DrawerLayout if is open and in second onBackPressed intent to another activity


How can i change my cod that on the first back pressed close drawer Layout if is open and in second back pressed intent to another activity if drawer is close ?

my drowrlayout is :

 drawerLayout = (DrawerLayout) findViewById(R.id.downMenu);
                if (m == false) {
                    m = true;
                    drawerLayout.openDrawer(Gravity.LEFT);
                } else {
                    m = false;
                    drawerLayout.closeDrawer(Gravity.LEFT);

                }

Solution

  • You just need to check for it in onBackPressed()

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        } else {
           // DO your stuff here 
        }
    }
    

    Change the GravityCompat as per your need if you are using left drawer then it will be as GravityCompat.START .