Displaying selection dialogs is a common requirement in Android apps—whether prompting users to select a theme, choose a export file format, or pick a network server. Using MaterialAlertDialogBuilder ensures your dialog popups automatically comply with Material Design guidelines and adapt to dark mode seamlessly.
Production Implementation: Single-Choice Radio Option Dialog
Below is a complete Kotlin snippet showing how to launch a single-choice option dialog on a button click:
package com.example.myapp
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate()
setContentView(R.layout.activity_main)
val showDialogBtn = findViewById<Button>(R.id.btn_show_options)
showDialogBtn.setOnClickListener {
showSingleChoiceDialog()
}
}
private fun showSingleChoiceDialog() {
val options = arrayOf("Light Theme", "Dark Theme", "System Default")
var checkedItem = 1 // Default selected index ("Dark Theme")
MaterialAlertDialogBuilder(this)
.setTitle("Select Application Theme")
.setSingleChoiceItems(options, checkedItem) { _, which ->
checkedItem = which // Update selected index
}
.setPositiveButton("Apply") { dialog, _ ->
val selectedOption = options[checkedItem]
Toast.makeText(this, "Selected: $selectedOption", Toast.LENGTH_SHORT).show()
dialog.dismiss()
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.dismiss()
}
.show()
}
}Key Dialog APIs Breakdown:
`setSingleChoiceItems(items, checkedIndex, listener)`: Creates a radio button selection list where only one item can be picked at a time.
`MaterialAlertDialogBuilder`: Inherits theme colors automatically from your app’s
Theme.Material3setup.
Comments and corrections