Output:
1/ Modify activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/exitButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Exit"
android:textSize="18sp" />
</RelativeLayout>
2/ Modify MainActivity.kt
package com.zissofworks.exitalart
import android.app.AlertDialog
import android.os.Bundle
import android.widget.Button
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity() : AppCompatActivity() {
private lateinit var exitButton:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
exitButton = findViewById(R.id.exitButton)
exitButton.setOnClickListener {showAlertDialogue()}
onBackPressedDispatcher.addCallback(object: OnBackPressedCallback(enabled = true){
override fun handleOnBackPressed() { showAlertDialogue() }
})
}
private fun showAlertDialogue() {
val builder: AlertDialog.Builder = AlertDialog.Builder(this@MainActivity)
builder.setMessage("Are You Sure You want to exit?")
builder.setPositiveButton("Yes") { _, _ -> finish() }
builder.setNegativeButton("No") { _, _ -> }
val alertDialog: AlertDialog = builder.create()
alertDialog.show()
}
}