Android Kotlin: On back button pressed example

This example demonstrates how to customize the behavior of the back button press in an Android application written with Kotlin. The code focuses on the MainActivity.kt file, where the logic resides.

Breakdown of MainActivity.kt

The class MainActivity inherits from AppCompatActivity, which provides functionalities for most activities in an Android application.

  • onCreate: This method is called when the activity is first created. Here, it sets the layout for the activity using setContentView.

  • onBackPressed: This is the key method that gets called when the user presses the back button on the device. By default, this method simply finishes the activity, but we can override it to define custom behavior. In this example, the onBackPressed method creates an AlertDialog with two buttons: "Yes" and "No".

    • AlertDialog: This class helps build a dialog box with a message and action buttons. Here, the dialog title and message ask for confirmation before exiting the app.
    • setPositiveButton: This sets the action for the "Yes" button. If clicked, it calls super.onBackPressed(), which finishes the activity as intended.
    • setNegativeButton: This sets the action for the "No" button. If clicked, it simply shows a "Thank you" toast message.
    • setCancelable(true): This allows the user to dismiss the dialog by tapping outside of it.

Summary

This code snippet showcases how to intercept the back button press and provide a confirmation dialog before exiting the app. This improves user experience by giving them the option to choose and avoids accidental exits. The provided layout file (activity_main.xml) doesn't play a role in handling the back button press in this specific example.


MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    // called when the activity has detected the user's press of the back key.
    // the default implementation simply finishes the current activity,
    // but you can override this to do whatever you want.
    override fun onBackPressed() {
        AlertDialog.Builder(this).apply {
            setTitle("Please confirm.")
            setMessage("Are you want to exit the app?")

            setPositiveButton("Yes") { _, _ ->
                // if user press yes, then finish the current activity
                super.onBackPressed()
            }

            setNegativeButton("No"){_, _ ->
                // if user press no, then return the activity
                Toast.makeText(this@MainActivity, "Thank you",
                    Toast.LENGTH_LONG).show()
            }

            setCancelable(true)
        }.create().show()
    }
}
activity_main.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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#EDEAE0"
    tools:context=".MainActivity"/>
More android kotlin tutorials