Description: When user presses two times "back" button, he is allow to exit from activity
Complexity Level:
Beginner
Keywords: back,
back button, android, android studio, alert, onbackpress, twice
When we are doing some important operation or work on activity and it may possible that by mistake we pressed "back" button. This will simply stop all your important work and you are redirect to previous activity.
To overcome this situation, we can provide a confirmation to the user that you need to press once again to exit from activity. This will give user a great experience in application.
To add this functionality in you application, use following code snippet.
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press once again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
Expatiation:
doubleBackToExitPressedOnce is core of this snippet. When user presses "back" button, value for `doubleBackToExitPressedOnce` is "false" and he will get a message for "Press once again to exit".
If user presses "back" button one more time, he will redirect to previous activity as "doubleBackToExitPressedOnce" is now "true".
No comments:
Post a Comment