Overriding Back Button Behavior in Android Applications

Sometimes you might want to change the default behavior of the back button in your android application. For example, you might have a screen in which after filling out some information, the user has to press a button to send it to a remote server. In this situation, if the user accidentaly press the back button, he will loose all the info he had entered. So you should override its default behaviour and show a dialog box, so he can confirm he wants to quit the screen before it closes.

Android system navigation buttons

This is quite easy to accomplish. All you’ve got to do is override an event called onBackPressed() on your activity. In my example, I’m gonna show a dialog box for the user to confirm if he really wanna quit the screen. If the user chooses ‘Yes’, the activity will be finished immediately. Instead, if the chooses ‘No’, the dialog box will be closed and he will be able to keep navigating on the screen.

@Override
public void onBackPressed()
{
	// instantiates an alert dialog object and sets its properties
	AlertDialog.Builder alert = new AlertDialog.Builder(this);

	alert.setTitle("Leave screen?");
	alert.setMessage("Are you sure you wanna leave without saving?");

	// setting the alert caption and the event listener
	alert.setPositiveButton("Yes", 
		new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// closes the current activity
				finish();
			}
		});

	alert.setNegativeButton("No", 
		new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				// cancel the dialog
				dialog.cancel();
			}
		});

	// show the alert
	alert.show();
}
Advertisement