Disable back button press in android programmatically

How to turn off android phone device back button functionality dynamically.

Back button is used to go back inside android application if your application has more  then one activity and you have open multiple activities from your home activity then back button gives us the inbuilt facility to go back to previous activity. But some times app developer need to disable the back button, this can be possible through onBackPressed() method. So here is the complete step by step tutorial for Disable back button press in android programmatically.

android-project-download-code-button

How to Disable back button press in android programmatically.

Code for MainActivity.java file.

 package com.disablebackbutton_android_examples.com;

import android.app.Activity;
import android.os.Bundle;


public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 }
 
 @Override
 public void onBackPressed() {
 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.disablebackbutton_android_examples.com.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="BACK BUTTON DISABLE"
 android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>

Screenshot:

Disable back button press in android programmatically

Click here to download Disable back button press in android programmatically project with source code.