Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
How to Generate Dynamic Multiple Buttons in Android?
Next article icon

How to Disable Back Press Button in Android?

Last Updated : 02 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Physical keys on Android let users lock the phone, switch off the device, control volume, go back, go home and display background applications. Between all the keys, the back button is used the most in applications for navigating between activities. However, if the navigation stage reaches the start point on the continuous back press, the application shall not immediately close and ask for an input to close in any form like an AlterDialog. This is basically disabling the back button to exit the application and asking for user input.

Disable Back Press in Android

So in this article, we will show you how you could disable the back press in Android. Follow the below steps once the IDE is ready.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Geek!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>
                      
                       

Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin

package org.geeksforgeeks.backpress
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
  
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
  
    override fun onBackPressed() {
  
        // To execute back press
        // super.onBackPressed()
  
        // To do something else
        Toast.makeText(applicationContext, "Back Button Pressed", Toast.LENGTH_SHORT).show()
    }
}
                      
                       

Output:

You can see that the back press is disabled.

https://media.geeksforgeeks.org/wp-content/uploads/20220126141841/f4.mp4


Next Article
How to Generate Dynamic Multiple Buttons in Android?
author
aashaypawar
Improve
Article Tags :
  • Android
  • Kotlin

Similar Reads

  • How to Enable/Disable Button in Android?
    The Enable/Disable Feature is used in many Android apps so the basic use of that feature is to prevent the user from clicking on a button until they will add all the required fields that have been asked. We are considering an example of email and password if the user has entered the email and passwo
    3 min read
  • How to Make a Custom Exit Dialog in Android?
    In this tutorial, we are going to create a Custom Exit Dialog in Android. By default, android doesn't provide any exit dialog, but we can create it using the dialog class in java. But most of the developers and also the user don't like the default dialog box and also we can't do any modification in
    5 min read
  • How to Disable a Button in Flutter?
    Sometimes we need to make the button disabled, let us consider, you created a form to take the user input and a form submit button. Then you want that, the button must be disabled until the user fills all the fields of the form then immediately enable the button. Sample Output is given below what we
    3 min read
  • How to Generate Dynamic Multiple Buttons in Android?
    In Android Studio, buttons are graphical user interface (GUI) elements that users can click or tap to perform an action. Buttons are typically represented by a rectangular or rounded rectangular shape with a label or an icon. In this article, we will learn to make dynamic multiple buttons in android
    3 min read
  • How to Detect Long Press in Android?
    A Long Press refers to pressing a physical button or tap a virtual button on a touchscreen and holding it down for a second or two. Employed on touchscreens, smartphones, tablets, and smartwatches, the long press or long tap increases the user interface's flexibility. The typical "short press" or "s
    4 min read
  • How to Add Data to Back4App Database in Android?
    Prerequisite: How to Connect Android App with Back4App? Back4App is an online database providing platform that provides us services with which we can manage the data of our app inside the database. This is a series of 4 articles in which we are going to perform the basic CRUD (Create, Read, Update,
    4 min read
  • How to Set Buttons Inside an Alert Dialog in Android?
    In this article, we are going to see how can we set two buttons inside an Alert Dialog. For example, we can see when an alert dialog is pop up then their two types of buttons available one is the Ok or Positive Button another one is Cancel or Negative Button. Alert dialogs are most frequently used i
    4 min read
  • How to Delete Data in Back4App Database in Android?
    We have seen adding data to our Back4App database along with reading and updating this data. In this article, we will take a look at Deleting this data.  What we are going to build?  We will be adding a simple button inside our update screen where we were updating our data and inside that screen, we
    7 min read
  • How to Save Switch Button State in Android?
    In Android, a Switch is a type of button that lets the user toggle between two actions or instances. In general, a Switch is used for selecting one between two options that can be invoking any actions or functions. In this article, we are going to see how we can save the state of the Switch Button i
    3 min read
  • Double-Tap on a Button in Android
    Detecting a Double Tap on Button in Android i.e. whenever the user double taps on any Button how it is detected and according to the Button a response can be added corresponding to it. Here an example is shown in which the double tap on the Button is detected and the corresponding to it response is
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences