Dibas Dauliya
Dibas Dauliya

Reputation: 679

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);
    }

Upvotes: 1

Views: 84

Answers (2)

Karthik
Karthik

Reputation: 67

If your drawer is opened, first close then do the logic

@Override
public void onBackPressed() {
    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }
        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);
    }
}

Upvotes: 0

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15423

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

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

    return;
} 

Upvotes: 2

Related Questions