Coders' Guidebook

How to add a dialog window to your android app

Dialog windows are a great way of displaying information and asking for user input.

dialogwindow.png

To begin making a dialog window you first must create a new Kotlin file. Navigate through Project > app > java then right-click the folder with the name of your project. In the menu that opens select New > Kotlin File/Class.

new-kotlin-class.png

Set the name to 'DialogWindow' and the kind to 'Class' then press OK.

dialogclass.png

A file called 'DialogWindow.kt' should open in the editor.

The dialog window kotlin code

To create and modify the dialog window, you will need to import the DialogFragment class by typing the following command at the top of the DialogWindow.kt file:

import androidx.fragment.app.DialogFragment

In the main body of the DialogWindow.kt file, you will find the beginning of a class called DialogWindow.

class DialogWindow {
}

Complete the class so it looks similar to the following. We will explore the code in more detail in just a moment.

class DialogWindow : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val builder = AlertDialog.Builder(activity!!)

        builder.setMessage("Make a selection")
            .setPositiveButton("OK") { dialog, id ->
            }
            .setNegativeButton("Cancel") { dialog, id ->
            }

        return builder.create()
    }
}

In the above code, we have written an onCreateDialog function which (when called) loads the dialog window. The AlertDialog.Builder class is then used to introduce buttons and text into, and customise the layout of, the dialog window. AlertDialog.Builder takes the argument activity!!: a reference to an Activity class that will be used later by the MainActivity.kt file to open the dialog window.

Next, we use a variety of methods to create the content of the dialog window. The setMessage method displays text to the user (e.g. Make a selection), while setPositiveButton and setNegativeButton each represent buttons (OK and cancel, respectively). Positive buttons direct the dialog windows' action to proceed, negative buttons cancel the action, and neutral buttons (called using the setNeutralButton method) neither continue nor cancel the action (e.g. delay the decision until later). Each button type can only be used once per dialog window.

Finally, the return statement completes the function and dialog window. One thing you may notice about our code is it currently contains quite a few errors (several words will be red). We can fix some of these errors now by importing a couple of classes into the DialogWindow.kt file. For example, left-click the red Bundle word then press alt and enter on your keyboard. In the resulting drop-down menu select Import and android studio will import the missing Bundle class.

importbundle.png

Use the same process to import the missing Dialog and AlertDialog classes.

Using a button to load the dialog window

Let's now create a button that will load the dialog window when clicked. Load the XML layout file where you want the button to go. For example, you may like to use the activity_main.xml file which can be found by clicking Project > app > res > layout

activitymain.png

Drag and drop a button object from the Palette into the layout as described previously.

addbutton.png

If a red warning sign appears in the top-right corner of the editor window then you may need to press the infer constraints button to resolve the missing constraints error.

redwarning.png infer.png

Select the button and open the Attributes panel. Set the id to 'dialog_window' and the text to 'view dialog window' (note this may result in a hardcoded text warning which can be resolved as described previously).

dialogbutton.png

Moving on, let's now make the button operational by writing some code in the MainActivity.kt file. If the file is not already open then you can find it by clicking Project > app > java > folder for your project.

mainactivity.png

Add the following code to the MainActivity.kt file below the setContentView statement of the onCreate function:

val button = findViewById<Button>(R.id.dialog_button)

button.setOnClickListener {
    val myDialog = DialogWindow()
    myDialog.show(supportFragmentManager, "first_dialog")
}

The above code loads the dialog window when the button is clicked. If the word Button is underlined in red then you will need to select the word and press alt and enter on your keyboard to create the relevant import statement. The complete MainActivity.kt file should look like this:

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button

class MainActivity : AppCompatActivity() {

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

        val button = findViewById<Button>(R.id.dialog_button)

        button.setOnClickListener {
            val myDialog = DialogWindow()
            myDialog.show(supportFragmentManager, "first_dialog")
        }
    }
}

Congratulations! You have now created a dialog window! We will explore dialog windows further and run through some of the ways you can style them and make them functional in later tutorials.

dialogwindow.png

<<< Previous

Next >>>