Search code examples
javaandroiddrawerlayoutonbackpressed

click back twice to close app with toast in drawer layout


In my main activity there is drawer layout and by looking this i tried to add the feature which suggest users to click the back button twice to close the app

but in my case when closing the DrawerLayout it is showing toast message but i don't want that instead i want to show it when activity is free.

 boolean doubleBackToExitPressedOnce = false;

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);}
//        } else {
//            super.onBackPressed();
//        }
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

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

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);
    }

Solution

  • If your drawer is open then close it and return to avoid toast

    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    
        return;
    }