Android Custom AlertDialog Tutorial Using Kotlin

Whenever you need to show a custom message or alert on your app, then you need an Android custom AlertDialog. It is very easy to learn and implement! You want to show an alert containing a message? Or, you want to show a custom style alert? Then this tutorial is right for you.

Basically the alert message on Android is using an existing class from the Android framework and that is the AlertDialog. It has many styles like displaying a simple alert message, a multiple choices alert, a list of items alert, a custom layout alert dialog, etc.

What the app will look like?

The app will look like this after you finish this tutorial:

What will you learn?

  • Understand how to implement and show an AlertDialog on the Android app.
  • Learn about different types of AlertDialog (simple, multiple choices, list of items, custom layout, etc) and use some of them.
  • Implement the listener from AlertDialog buttons.

Note: In this post, I used Android Studio 3.5.3, make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.61.

Getting Started – Android Custom AlertDialog

Open your Android Studio and choose to Start a new Android Studio Project. Then set the Application Name CustomAlertDialog and select Kotlin as the language. Give the Activity Name MainActivity and wait until the Android Studio finishes preparing your project.

Open activity_main.xml inside res/layout directory and replace the code given below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center">

   <Button
       android:id="@+id/btSimpleAlert"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Simple Alert"
       />

   <Button
       android:id="@+id/btMultipleChoices"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Multiple Choices"
       />

   <Button
       android:id="@+id/btListOfItems"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="List of Items"
       />

   <Button
       android:id="@+id/btCustomLayout"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Custom Layout"
       />

   <Button
       android:id="@+id/btContainsEditText"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Contains EditText"
       />

</LinearLayout>

That’s it for the first step of creating a screen that contains some buttons to show each alert dialog later.

Next, open MainActivity.kt file and add each of these functions:

Simple AlertDialog

Add a new function showSimpleAlert() here:

private fun showSimpleAlert() {
   AlertDialog.Builder(this)
       .setTitle("Simple Alert")
       .setMessage("This is a simple alert dialog")
       .setPositiveButton("OK") { dialog, which ->
           Toast.makeText(applicationContext, "OK is pressed", Toast.LENGTH_LONG).show()
       }
       .setNegativeButton("Cancel") { dialog, which ->
           Toast.makeText(applicationContext, "Cancel is pressed", Toast.LENGTH_LONG).show()
       }
       .setNeutralButton("Neutral") { dialog, which ->
           Toast.makeText(applicationContext, "Neutral is pressed", Toast.LENGTH_LONG).show()
       }
       .show()
}

There are some methods or function from AlertDialog that we use here:

  • setTitle() is for giving the dialog a title.
  • setMessage() is setting a message for the dialog.
  • setPositiveButton(). This method is for giving the dialog a positive button and its listener/action when the button is pressed.
  • setNegativeButton()
  • setNeutralButton()
  • show(), this function is to show the AlertDialog.
simple alertdialog

List of Items AlertDialog

Add a new function showListAlert() here:

private fun showListAlert() {
   val items = arrayOf("Bird", "Cat", "Dog", "Fish", "Chicken")

   AlertDialog.Builder(this)
       .setTitle("List of Pets Dialog")
       .setItems(items) { dialog, which ->
           Toast.makeText(applicationContext, "${items[which]} is pressed", Toast.LENGTH_LONG).show()
       }
       .setNegativeButton("Cancel") { dialog, which ->
           Toast.makeText(applicationContext, "Cancel is pressed", Toast.LENGTH_LONG).show()
       }
       .show()
}

The setItems() function takes a parameter that is an Array of Strings as a list of items for it.

list of items alert dialog

Multiple Choices AlertDialog

Add a new function showMultipleChoicesAlert() here:

private fun showMultipleChoicesAlert() {
   val selectedList = ArrayList<Int>()

   val items = arrayOf("Bird", "Cat", "Dog", "Fish", "Chicken")

   AlertDialog.Builder(this)
       .setTitle("Multiple Choices Dialog")
       .setMultiChoiceItems(items, null) { dialog, which, isChecked ->
           if (isChecked) {
               selectedList.add(which)
           } else if (selectedList.contains(which)) {
               selectedList.remove(which)
           }
       }
       .setPositiveButton("OK") { dialog, which ->
           val selectedItems = ArrayList<String>()

           for (i in selectedList.indices) {
               selectedItems.add(items[selectedList.get(i)])
           }
           Toast.makeText(applicationContext,
               "Selected items: " + Arrays.toString(selectedItems.toArray()),
               Toast.LENGTH_SHORT).show();
       }
       .show()
}

The setMultiChoiceItems() is also takes a parameter of Array of Strings. There is also a conditional (isChecked) to point out which items that have already been selected.

custom multiple choices alertdialog

Custom AlertDialog

Add a new function showCustomAlert() here:

private fun showCustomAlert() {
   val dialogView = layoutInflater.inflate(R.layout.dialog_custom_layout, null)

   val customDialog = AlertDialog.Builder(this)
       .setView(dialogView)
       .show()

   val btDismiss = dialogView.findViewById<Button>(R.id.btDismissCustomDialog)
   btDismiss.setOnClickListener {
       customDialog.dismiss()
   }
}

Create a new layout resource file named dialog_custom_layout.xml and put this code inside it:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:orientation="vertical">

   <TextView
       android:layout_width="match_parent"
       android:layout_height="80dp"
       android:background="@drawable/ic_launcher_background"
       android:text="Custom Dialog"
       android:textSize="20sp"
       android:textColor="@android:color/white"
       android:gravity="center"
       />

   <TextView
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="This is a custom dialog message"
       android:textSize="16sp"
       android:gravity="center"
       android:layout_marginTop="40dp"
       android:layout_marginBottom="40dp"
       />

   <View
       android:layout_width="match_parent"
       android:layout_height="1dp"
       android:background="#DEDEDE"
       />

   <Button
       android:id="@+id/btDismissCustomDialog"
       android:layout_width="match_parent"
       android:layout_height="50dp"
       android:background="?selectableItemBackground"
       android:text="Dismiss"
       />

</LinearLayout>

The setView() is a method to set the custom view or layout of the dialog. In this case, we inflate the dialog_custom_layout.xml to the view and put is as a parameter to setView().

android custom alertdialog

EditText AlertDialog

Add a new function showSimpleAlert() here:

private fun showEditTextAlert() {
   val editText = EditText(this)
   val layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
       LinearLayout.LayoutParams.MATCH_PARENT)
   editText.setLayoutParams(layoutParams)

   AlertDialog.Builder(this)
       .setTitle("EditText Alert")
       .setMessage("Please input your name..")
       .setView(editText)
       .setPositiveButton("OK") { dialog, which ->
           Toast.makeText(applicationContext, "Your name is ${editText.text.toString()}",
               Toast.LENGTH_LONG).show()
       }
       .setNegativeButton("Cancel") { dialog, which ->
           Toast.makeText(applicationContext, "Cancel is pressed", Toast.LENGTH_LONG).show()
       }
       .show()
}

It is similar to the custom dialog style before, but the difference is the view is created programmatically. This example is an EditText.

custom edittext alertdialog

So, that is all for AlertDialog types for this tutorial. The next step is setting the listeners for each button that you created earlier. Open MainActivity.kt again, and modify the onCreate() method.

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

   btSimpleAlert.setOnClickListener {
       showSimpleAlert()
   }

   btListOfItems.setOnClickListener {
       showListAlert()
   }

   btMultipleChoices.setOnClickListener {
       showMultipleChoicesAlert()
   }

   btCustomLayout.setOnClickListener {
       showCustomAlert()
   }

   btContainsEditText.setOnClickListener {
       showEditTextAlert()
   }
}

And now it is time to run the app and see the dialogs yourself!

Where to go next?

You can download this full code from the link below:

Download final code

Be sure to check my other cool posts here about:

Hope you like my post, comment and share it with love!

You may also like...

Join the discussion...

This site uses Akismet to reduce spam. Learn how your comment data is processed.