Reading Time: 9 minutes

In this third part of Android Alert Dialogs in Kotlin, we will review how to add choices to dialogs with lists, which can be of three kinds: traditional lists, radio buttons and checkboxes.

If you want to see the previous parts of this tutorial, take a look at them here:

In the first part of this Android Alert Dialogs in Kotlin tutorial we talked about the importance of Dialogs in Android and Kotlin, the setup we did in that part of the series, is the building blocks of any other work you will need to create alerts. In the second part, we reviewed buttons, which are the most common way to interact with alerts. But there are many more things you may need to add in those dialogs, in this tutorial you will learn how to add lists of choices to your dialogs, which are divided into three categories:

  1. Pure text lists, where you can choose one option.
  2. Radio buttons lists, also for a single option.
  3. Checkboxes lists, for choosing multiple options.

Just as the last time we will start with the project we finished on part 2, if you don’t have it or want to download it, get it in here:

If you downloaded the sample project run it and you will be able to see something like the following image:

Adding more buttons to display the dialogs

Before working with this app, we will add 4 more buttons to the UI for each of the new alerts, this way you will keep all your examples and reuse them in your personal projects.

Setting up new buttons

Add the following code to activity_main.xml, below your previous button:

<Button
        android:id="@+id/button_traditional_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showBasicDialog"
        android:text="Show single-choice list!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

This code is very similar to the previous button, but there are 3 important things to notice:

  1. The first line has an id. IDs are important to manipulate views in code and be able to reference them. You will see why I added this.
  2. The onClick method still points to showBasicDialog, this will change after we create the method that shows the list, but for now, leave it like this to avoid errors from Android Studio.
  3. We have changed the text of the button to another.

Build and run the app and you should get the following.

If you look at it, you should notice the new button is placed over the previous button, this is why we added the ID. Put an ID to your previous button:

<Button
    android:id="@+id/button_basic_dialog"
        .
        .
        ./>

I prefer to add them as the first item of the XML items to spot them easily, but it can be placed anywhere. Now notice both buttons have some lines that make reference to constraints layout_constraintX_toYOf. In the mobile development world, meaning Android and iOS, it is common to manage the views with constraints. These constraints basically tell the items, where to locate themselves in the screen, if you look at both buttons they are constrained to the ‘parent‘, meaning they have an equal distance to the top, bottom, right, and left of the screen. In order to show both buttons, we need to put the bottom constraint of the first button, relative to the top constraint of the second button. This is why the IDs are needed here.

Constraints

Change the first button’s layout_constraintBottom_toBottomOf, for the following:

app:layout_constraintBottom_toTopOf="@id/button_traditional_list"

Note that the bottom is now constrained to the “toTopOf” while before it was “toBottomOf“.

In the second button change layout_constraintTop_toTopOf, for:

app:layout_constraintTop_toBottomOf="@id/button_basic_dialog"

Note: It is not necessary to add both, layout_constraintBottom_toTopOf and layout_constraintTop_toBottomOf, but you get more practice and sense of the logic if you add them all.

Now run the app again and you should be able to see both buttons. At the moment they will both show the same dialog as they are both referencing showBasicDialog action.

Adding the rest of the buttons

Add two more buttons, for with the text “Show radio button list!” and “Show checkboxes list!”.

Click on the buttons below to get a hint or view the full answer (double click on the code box to show the hidden code). But before, try to do it by yourself!

Hint 1: Put a unique id for each button you add, like we did above:

android:id="@+id/your_button_id"

Hint 2: To place a button below another one you need to reference:

layout_constraintTop_toBottomOf = "id_of_the_button_above"

while for the other view at the top you add:

layout_constraintBottom_toTopOf = "id_of_the_button_below"

<Button
        android:id="@+id/button_radio_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showBasicDialog"
        android:text="Show radio button list!"
        app:layout_constraintBottom_toTopOf="@id/button_checkbox_list"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button_traditional_list" />

    <Button
        android:id="@+id/button_checkbox_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="showBasicDialog"
        android:text="Show checkbox list!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button_radio_list" />

With the four buttons added you should be seeing the following in the screen:

Done with the preparation, let’s dive into the dialogs.

Android Dialogs with Lists

As mentioned at the beginning of this article, Android gives three main options of lists to add in a dialog: with pure texts and no indicators, with radio buttons and with checkboxes.

Adding a selectable list of text

This first type of list is called in the Android documentation a “traditional single-choice list”.

Go to MainActivity.kt and create a new function:

fun showTraditionalListDialog(view: View?) {
  ...
}

For any of the lists, you will need to create an array with the items you want to display. Imagine you want to ask the user for his favorite hobbies, add the array inside of the function, and add the choices like this:

 val hobbies = arrayOf("VideoGames", "Reading", "Sports", "Movies")

Next, add the code to create the dialog.

//1
val builder = AlertDialog.Builder(this)
builder.setTitle("Traditonal List")
//2
builder.setItems(hobbies, DialogInterface.OnClickListener { 
  dialog, which ->
    //3
    // 'which' item of the 'dialog' was selected
    Toast.makeText(applicationContext, hobbies[which], 
                   Toast.LENGTH_SHORT).show()
        })
//4
builder.show()

Let’s review the code above:

  1. Any dialog needs a builder, this builder is always created the same way. The ‘this’ word refers to the context of the application. We also add a title but note this is not necessary.
  2. You set the items in the ‘hobbies’ array to the builder, so it knows you are providing a list. Add the OnClickListener method to let it know what to do when an item is clicked.
  3. As you did in the basic example, when a user selects an item, you will be showing a toast. Note that the second parameter is now referencing the item of the array “which” was clicked. Note it gives an index, so you will be referencing hobbies[1] and that will give you the string to display in the toast.
  4. You need to let the builder know it has to be shown. Remember this, I often forget it and it ends up in long hours of wondering what is wrong. Note the same applies to the toast, it’s easy to forget to put the ‘show()’ in the end.

Now, go to your activity_main.xml file and reference the function, by changing the content in the onClick method of the corresponding button:

android:onClick="showTraditionalListDialog"

Run the app and click the Show single-choice List button. You should be seeing something like the image below:

Adding a radio button list

If you got the previous point working I have good news for you! Adding a list with radio buttons and with checkmarks (our next point) is almost the same as the ‘traditional list’, but keep going so you can practice and master dialogs.

For this one, we need to keep track of the selected item, so outside of the function, we will create a variable for this:

    private var selectedRadioItem = -1

The reason why we add -1 is to ‘not choose any’, you may want to start your dialog with no pre-selected choice.

Next, as we did in the others, create a function, in this case, called showRadioButtonListDialog:

fun showRadioButtonListDialog(view: View?) {
  ...
}

The code to add inside the function is the following:

// 1
val cities = arrayOf("New York", "London", "Hong Kong", "Río")
// 2
val builder = AlertDialog.Builder(this)
builder.setTitle("Radio Button List")
// 3
builder.setSingleChoiceItems(cities, selectedRadioItem,
            DialogInterface.OnClickListener { dialog, which ->
                //4
                selectedRadioItem = which
                Toast.makeText(applicationContext, cities[which],
                                   Toast.LENGTH_SHORT).show()
            })
// 5
builder.setPositiveButton("OK") { dialog, which ->
    dialog.dismiss()
}
// 6
builder.show()

Again let’s look at the code step by step:

  1. You create an array of cities, imagine you want your user to choose in which city they want to live, because with technology everything is possible, so we have those 4 cities to give them as an option.
  2. As mentioned above, every dialog needs a builder. And once again we add the title.
  3. Now for our first change, you will see the items are now added through the method setSingleChoiceItems(), this is telling the builder you want a radio button list. The difference between this and the setItems() method above, is that this one is receiving the ‘default’ item, which is the variable you created previously called selectedRadioItem.
  4. You set the selectRadioItem to the newly chosen item. The reason for creating this variable outside of the function is to save the chosen item, otherwise, the saved value would be overwritten every time we called the function. As you did before, you are outputting a toast to see if your choice was correct.
  5. For this kind of dialog, you are adding a confirmation button, because the user may still not be sure and want to change the choice once again until confirmation.
  6. Once again, remember to show the dialog.

Now a question, after this we have one more step before seeing our new dialog, do you remember it?

You need to add the method to the onClick of the button in activity_main.xml

android:onClick="showRadioButtonListDialog"

Run the app once again and see the result of the changes by clicking to the show radio button list item, you can see an image below for reference:

Adding a checkmark list

I hope by now you are getting a sense of how alerts work, otherwise don’t worry, software development is about practice, and that’s why we will now do it again with a checkmark list.

As you did with the radio buttons you need to create a variable outside of the function to keep track of which items are checked, this can be done through an array of boolean items:

private var selectedList = booleanArrayOf(false, false, false, false)

Now, create a function called showCheckmarkList to show this last dialog:

fun showCheckmarkList(view: View?) {
  ...
}

For the code inside the function we will have the following:

//1
val fruits = arrayOf("Orange", "Banana", "Watermelon", "Grapefruit")
//2
val builder = AlertDialog.Builder(this)
builder.setTitle("Checkmark List")
//3
builder.setMultiChoiceItems(fruits, selectedList,
           DialogInterface.OnMultiChoiceClickListener { 
             dialog, which, isChecked ->
               //4
               selectedList.set(which, isChecked)
               Toast.makeText(applicationContext, fruits[which],
                 Toast.LENGTH_SHORT).show()
})
//5
builder.setPositiveButton("Ok") { dialog, which ->
    dialog.dismiss()
}
//6
builder.show()

Let’s review each part of the code as we did before to see what it is all about.

  1. The array of items we are displaying in the dialog.
  2. You create the builder that is needed for every dialog.
  3. In this case, you are using ‘setMultiChoiceItems’ to show the checkmark list. This method is very similar, like the one for radio buttons, with the only difference that it receives our array of booleans to keep track of checked items.
  4. You check or uncheck items accordingly and once again you are showing a Toast with the selected item.
  5. With the same pattern as the radio button dialog, we need a button to confirm the choices.
  6. I will say it again, remember to show your builder.

We are only missing one step, can you remember what is it? Adding your method call to the onClick of the button.

android:onClick="showCheckmarkList"

Done! Run the app and your dialog should be working like in the image below.

That’s it for today! I hope everything has been easily understood and this Android Alert Dialogs Kotlin Tutorial was useful to you. If you want to see the result of this tutorial, you can download the item below

If you liked the content on this post, please subscribe at the bottom of the page. If you have any doubts don’t hesitate to leave a comment and I will reply as soon as possible. You can also donate a coffee to support me so I can keep on creating things like this!

Until next time!

Evana Margain Puig

(Visited 60 times, 2 visits today)