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"/>

- android kotlin - Get battery temperature programmatically
- android kotlin - Get battery health programmatically
- android kotlin - Get battery status programmatically
- android kotlin - Get string resource by name
- android kotlin - Enable disable bluetooth programmatically
- android kotlin - Change screen orientation programmatically
- android kotlin - Change orientation without restarting activity
- android kotlin - Get screen size programmatically
- android kotlin - RecyclerView animation
- android kotlin - RecyclerView smooth scroll
- android kotlin - GridView selected item background color
- android kotlin - Border/divider between GridView items
- android kotlin - GridView OnItemClickListener
- android kotlin - TextView get width height programmatically
- android kotlin - TextView html formatted text