I'm new to Android development and I want it so when the user presses the back button on the main activity, a toast message appears with a "confirm exit by pressing the back button again" message. How would I do this? This is what I have so far:
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Toast s = Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG);
s.show();
wait();
public boolean onBackPressed() {
finish();
}
}
work perfectly in my case
Best and simple solution with Toast
I would just save the time of the backpress and then compare the time of the latest press to the new press.
You can also dismiss the toast when the app the back press is confirmed (cred @ToolmakerSteve):
In newer version you can use the snackbar instead of toast.
After having to implement the same behaviour many a times, decided to go aboiut building a library for the same :
DoubleBackPress Android Library
. It provides many easy to use templates and the double back press behaviour without all the hassle.Just do :
Finally, override the onBackPressed with DoubleBackPress behaviour for the back press.
Example GIF for similar behaviour