Wednesday, February 7, 2018

android kotlin - AlertDialog example

Kotlin AlertDialog
The AlertDialog is a subclass of Dialog in android native SDK. An AlertDialog can display one, two, or three Buttons inside its interface. Developers can display only text in the dialog box or text with buttons or even they can build a complex dialog view using a custom layout.

The following android application development tutorial will demonstrate to us how we can build and show an AlertDialog to the app user interface using the Kotlin programming language. In this tutorial, we also implement the AlertDialog Button’s click listeners.

The AlertDialog.Builder() creates a ‘Builder’ object instance for an alert dialog that uses the default alert dialog theme. This method requires passing a ‘Context’. This AlertDialog Builder has several useful methods to build an instance of AlertDialog.

The AlertDialog Builder setTitle() method sets the title text for the dialog window. The setMessage() method sets the alert dialog message. The setCancelable() method sets whether the alert dialog is cancelable or not. Default is cancelable. The setIcon() method shows an icon at the start of the alert dialog’s title.

The setPositiveButton() allows us to set a positive Button for the dialog window and also set a click listener for this positive button. The setNegativeButton() allows us to set a negative Button with a click listener and the setNeutralButton() sets a neutral Button with its click listener.

Finally, the alert dialog builder object’s create() method creates an AlertDialog with the arguments supplied to the builder. To display the AlertDialog to the app interface, the AlertDialog show() method starts the dialog and displays it on screen.

This android kotlin tutorial code is written in an android studio IDE. Copy the code and paste it into your android studio IDE and run it on an emulator to test how we create an AlertDialog and display it on the app screen in an android application.

And how we implemented the AlertDialog buttons with click listener. We displayed screenshots of the emulator screen, which also help you to understand the code without running it on an android device or emulator.
MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.AlertDialog
import android.graphics.Color
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

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

        // Get the context
        context = this;

        // Get the widgets reference from XML layout
        val rootLayout = findViewById<ConstraintLayout>(R.id.rootLayout)
        val button = findViewById<Button>(R.id.button)

        // Button click listener
        button.setOnClickListener{
            // Initialize a new instance of alert dialog builder
            val builder = AlertDialog.Builder(context)

            // Set the alert dialog title
            builder.setTitle("App Background Color")

            // Display a message on alert dialog
            builder.setMessage(
                "Do you want to change the background?"
            )

            // Set a positive button and its click listener
            builder.setPositiveButton("YES"){dialog, which ->
                // Change the app background color
                rootLayout.setBackgroundColor(
                    Color.parseColor("#D6CADD")
                )
                // Do something when user press the positive button
                showToast("Ok, Background color changed.")
            }

            // Set the dialog dismissible on outside click
            builder.setCancelable(true)

            // Set the dialog on dismiss listener
            builder.setOnDismissListener {
                showToast("Dialog dismissed.")
            }

            // Display a negative button on alert dialog
            builder.setNegativeButton("No"){dialog,which ->
                showToast("You are not agreed.")
            }

            // Display a neutral button on alert dialog
            builder.setNeutralButton("Cancel"){_,_ ->
                showToast("You cancelled the dialog.")
            }

            // Finally, make the alert dialog using builder
            val dialog: AlertDialog = builder.create()

            // Display the alert dialog on app interface
            dialog.show()
        }
    }


    // Show toast message
    private fun showToast(message:String){
        Toast.makeText(context,message,Toast.LENGTH_SHORT).show()
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:id="@+id/rootLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp"
    android:background="#DCDCDD">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Me Alert Dialog"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
More android examples