Introduction
This code demonstrates how to create a single-choice alert dialog in an Android application written in Kotlin. The dialog allows users to select their favorite color from a predefined list. The user's selection is then displayed in a TextView on the main activity screen.
Breakdown of the Code
MainActivity.kt
- This file contains the main activity code responsible for handling user interactions and displaying the UI.
- The
onCreate
function sets up the activity by referencing the Button and TextView widgets defined in the activity layout (activity_main.xml
). - A
selectedIndex
variable is initialized to -1, indicating no initial selection. - The button click listener creates an alert dialog builder using
MaterialAlertDialogBuilder
. - The dialog title is set to "Which is your favorite?".
- A list of color options is defined as an array named
colors
. setSingleChoiceItems
method populates the dialog with thecolors
array and sets the initial selection usingselectedIndex
. No custom action is defined for individual item selection here.- Positive button ("Submit") is created. Clicking it retrieves the selected item position from the dialog's ListView and updates the TextView with the chosen color if a selection is made.
- Negative ("No") and Neutral ("Cancel") buttons are added without any specific actions.
- The dialog is set to be non-cancelable by the user.
- The dialog is built and displayed using
show
. - Initially, the positive button is disabled.
- An
onItemClickListener
is set on the dialog's ListView. Clicking a color option enables the positive button and updates theselectedIndex
.
activity_main.xml
- This file defines the layout for the main activity screen.
- It contains a Button labeled "Show Dialog" that triggers the alert dialog upon clicking.
- A TextView displays the user's selected favorite color.
build.gradle
- (Dependency Section Not Shown)
- This section specifies the libraries used in the project. Here, it shows the inclusion of the Material Design library (
com.google.android.material:material:1.6.1
) which provides theMaterialAlertDialogBuilder
class used for creating the dialog.
Summary
This code effectively demonstrates the creation of a single-choice alert dialog in Kotlin for Android. The code utilizes various methods like setSingleChoiceItems
, button click listeners, and list view item click listener to handle user interactions and update the UI based on selections. The initial disabling of the positive button ensures it's only enabled when a color choice is made, improving user experience.
package com.cfsuman.kotlintutorials
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val context:MainActivity = this
// get the widgets reference from XML layout
val button = findViewById<Button>(R.id.button)
val textView = findViewById<TextView>(R.id.textView)
// initial selection (-1 none)
var selectedIndex:Int = -1
button.setOnClickListener {
val builder = MaterialAlertDialogBuilder(context)
// dialog title
builder.setTitle("Which is your favorite?")
val colors = arrayOf(
"African violet",
"Alice blue",
"Alloy orange",
"Android green",
"Amaranth pink",
"Antique bronze"
)
// set single choice items
builder.setSingleChoiceItems(
colors, // array
selectedIndex
){dialog, i ->}
// alert dialog positive button
builder.setPositiveButton("Submit"){dialog,which->
val position = (dialog as AlertDialog)
.listView.checkedItemPosition
// if selected, then get item text
if (position !=-1){
val selectedItem = colors[position]
textView.text = "Favorite color : $selectedItem"
}
}
// alert dialog other buttons
builder.setNegativeButton("No",null)
builder.setNeutralButton("Cancel",null)
// set dialog non cancelable
builder.setCancelable(false)
// finally, create the alert dialog and show it
val dialog = builder.create()
dialog.show()
// initially disable the positive button
dialog.getButton(AlertDialog.BUTTON_POSITIVE)
.isEnabled = false
// dialog list item click listener
dialog.listView.onItemClickListener =
AdapterView.OnItemClickListener {
parent, view, position, id ->
// enable positive button when user select an item
dialog.getButton(AlertDialog.BUTTON_POSITIVE)
.isEnabled = position != -1
// set the current selected index
selectedIndex = position
}
}
}
}
<?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"
android:background="#DCDCDC"
android:padding="24dp">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Dialog"
android:textAllCaps="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/button" />
</androidx.constraintlayout.widget.ConstraintLayout>
// Material components
implementation 'com.google.android.material:material:1.6.1'