Controlling Back Button Behavior in Android
How to override or disable the hardware back button in Android, with guidance on when and why to use this approach.
There are scenarios where you need to intercept or disable the hardware back button in Android. Without handling it explicitly, users may inadvertently exit your application when they intend to navigate within it.
**Important:** If you disable the back button, always provide an alternative way for the user to close the application or navigate backward.
Disabling the Back Button
Override onBackPressed() with an empty implementation:
@Override
public void onBackPressed() {
// Back button disabled
}
Adding a Confirmation Dialog
A more user-friendly approach is to prompt for confirmation before exiting:
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", (dialog, which) -> finish())
.setNegativeButton("No", null)
.show();
}
Use this technique judiciously. Overriding expected navigation behavior can frustrate users if not implemented thoughtfully with clear alternative pathways.