How to change back button behaviour in android

How to modify overriding back button working so it will display custom Alert Dialog with Are you sure want to exit Yes,No button.

Normally without overriding  back button it will used to only exit form any current opening activity but by overriding back button functionality developer can do any this on back button press like displaying a custom build alert dialog containing two custom buttons yes, no and if user clicks on Yes it will exit from application and no is for close the alert dialog box so user can stay on current activity. So here is the complete step by step tutorial for How to change back button behaviour in android.

android-project-download-code-button

How to change back button behaviour in android.

Code for MainActivity.java file.

 package com.changebackbuttonbehaviour_android_examples.com;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class MainActivity extends Activity {

 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 }
 
 //overriding back button
 
 @Override
 public void onBackPressed() {
 
// Below code calls on back button clicked so define anything in this will run on
// back button.
 
 
 AlertDialog.Builder BackAlertDialog = new AlertDialog.Builder(MainActivity.this);
 
 BackAlertDialog.setTitle("Activity Exit Alert");
 
 BackAlertDialog.setMessage("Are you sure want to exit ?");
 
 
 BackAlertDialog.setPositiveButton("NO",
 new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {
 
 //Cancel alert dialog box .
 dialog.cancel();
 }
 });
 
 BackAlertDialog.setNegativeButton("YES",
 new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {
 
 
 
 //Exit from activity.
 finish();
 }
 });
 
 BackAlertDialog.show();
 
 return;
 }
 
}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.changebackbuttonbehaviour_android_examples.com.MainActivity" >

 

</RelativeLayout>

Screenshot:

How to change back button behaviour in android

Click here to download How to change back button behaviour in android project.