MaAc MaAc - 3 months ago 20
Java Question

How to handle twice to exit features with navigation drawer

I am using a simple navigation drawer

Activity
with some fragments. I also implemented doubleBackToExitPressedOnce method under
onBackPressed()
. Where already defined the navigation drawer open and close action for back press. So I modified the code like:

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
assert drawer != null;

if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else if (doubleBackToExitPressedOnce) {
super.onBackPressed();
}

this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}


Now my problem is when the navigation drawer open, I click on back button for close it first and then I want to exit from app. But every time it will display "Press again to exit". Which is very annoying in some cases. Please help me.

Answer

Make drawer an instance variable in your Activity:

DrawerLayout drawer;

Initialize it in onCreate():

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

And then, something like this should work:

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
    } else {
        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }
}