How to create an alert dialog with a list in Android(Kotlin)

How to create an Alert Dialog with a list in Android using Kotlin:

In our last tutorial, we learned how to create a simple alert dialog in android. In this post, we will learn how to create a list of items in an Alert Dialog.

It will be a simple list and the user can select any one of the items from the list.

We will use the same project that we created in our last post.

Android Alert Dialog with a list of items:

The first thing we need here is the list to show to the user. The list we will store in a resource file as it is easier to manage if we put it in a resource file.

In the res->values folder, right click -> new and click on Values resource file. Set a name of the file and click on OK to create that file.

This file we will use to store the list to show. Inside this file, we will keep an array. We can create one array as like below:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="popup_array">
        <item>Option 1</item>
        <item>Option 2</item>
        <item>Option 3</item>
        <item>Option 4</item>
        <item>Option 5</item>
    </string-array>
</resources>

Inside string-array, we can add all the values that we want to show in the dialog. Using the name, we can access this array.

So, we can change our MyDialog.kt file as below:

import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import java.lang.IllegalStateException

class MyDialog : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let{
            val alertBuilder = AlertDialog.Builder(it)

            alertBuilder.setTitle("Select an option")
            alertBuilder.setItems(R.array.popup_array, DialogInterface.OnClickListener{dialog, index ->
                Toast.makeText(it, index.toString(), Toast.LENGTH_SHORT).show()
            })
            alertBuilder.create()
        } ?: throw IllegalStateException("Exception !! Activity is null !!")
    }
}

Here,

  • We are creating one alert dialog builder using the Builder method call.
  • To the builder, we are setting one title.
  • The items those are created in the last step are added to the builder using the setItems method. The index is received on clicking of any item in the list. We are showing one Toast message on click.

This class can be used as like below:

MyDialog().show(supportFragmentManager, "mydialog")

If you run this app, it will create one dialog as like below: Android simple dialog with list

If we have a large set of values, the dialog will grow and it will become scrollable.

Android dialog list growable

You might also like: