1

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);
    }
Dibas Dauliya
  • 639
  • 5
  • 20

2 Answers2

2

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

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

    return;
} 
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
  • great, can you suggest me? will it be good to use toast or snackbar in such? – Dibas Dauliya Jan 21 '20 at 09:45
  • Both are correct way to inform user. But `snackbar` is a modern way to show something to user. In such a simple thing I think toast is enough to inform user about the action – Md. Asaduzzaman Jan 21 '20 at 09:47
  • can you please suggest how can I use it? i know it is normal condition but it seems to be quite complex to me in this condition, will you please help? – Dibas Dauliya Jan 21 '20 at 09:49
  • 2
    In your case since no action is required from user I think simple toast is enough to fulfill requirement. But if you want then can use like this way: `Snackbar.make(findViewById(android.R.id.content), "Please click BACK again to exit", Snackbar.LENGTH_SHORT).show()` – Md. Asaduzzaman Jan 21 '20 at 09:54
0

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);
    }
}
Karthik
  • 59
  • 3