How to create a SingleChoice AlertDialog in Android (Kotlin)

     DESCRIPTION     

In this tutorial we will create alert dialog with single choice from list of items. We will create a button that show alert dialog when that button is clicked, a TextView that shows the selected item from dialog.
SingleChoice AlertDialog in Android (Kotlin)

     VIDEO     


     SOURCE CODE     

Step 2: Code

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:padding="20dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/showAlertDialogBtn"
        android:text="Show Alert Dialog"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/txtView"
        android:text="Selected Item"
        android:textSize="20sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity.kt
package com.blogspot.atifsoftwares.myapplication

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.app.AlertDialog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

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

        showAlertDialogBtn.setOnClickListener {
            val listItems = arrayOf("Item 1", "Item 2", "Item 3")
            val mBuilder = AlertDialog.Builder(this@MainActivity)
            mBuilder.setTitle("Choose an item")
            mBuilder.setSingleChoiceItems(listItems, -1) { dialogInterface, i ->
                txtView.text = listItems[i]
                dialogInterface.dismiss()
            }
            // Set the neutral/cancel button click listener
            mBuilder.setNeutralButton("Cancel") { dialog, which ->
                // Do something when click the neutral button
                dialog.cancel()
            }

            val mDialog = mBuilder.create()
            mDialog.show()
        }

    }
}

Step 3: Output

SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)
SingleChoice AlertDialog in Android (Kotlin)

Comments

Popular posts from this blog

Manage External Storage Permission | Android Studio | Kotlin

Picture In Picture | Android Studio | Kotlin

Add a Back Button to Action Bar Android Studio (Kotlin)