Looking For Anything Specific?

Alert Dialog In Android With Kotlin - Sample Code

In this android kotlin tutorial, we are going to look into one of the must-know UI element of the android application development which is the Alert Dialog In Android, and we are going to create them with kotlin, I believe most of you have already known about which we mentioned briefly in the How to get runtime permission in the android post. Alternatively, if you are looking for an android bottom sheet you can refer to this tutorial: Bottom Sheet Android With Kotlin

What is An Alert Dialog? 

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

Source: Dialogs | Android Developers

So explained by android developers its small window that we give to the user to make a decision but there are much more use cases available for an android alert dialog, for example in some case you might want to give your user some pointers if they are missing out some information while filling out the forum, But be cautious, because we don't want to block the user from interacting so instead we can ask the information he/she missed out in the dialog this way the user can easily update and continue, so the use case for this modal UI is vast, only you have to decide when and how to show them.

How To Store And Read From Android SharedPreference In Kotlin

In Android, we can show an alert dialog in different ways, in which we are going to look into three ways which are to show a simple dialog without any modification, we can show a dialog as a fragment this will be helpful if you want to do some long operation like uploading an image and you want to apply Separation Of Concern this DialogFragments are the choice to go and incase if you wanted to show custom created UI instead of a simple Ok and Cancel button for that use case we will follow the custom dialog where we design and show it to the user.
 

How To Show An Alert Dialog With AlertDialog Builder:

A simple dialog is something that doesn't have a lot of customization and does a simple task alone or to represent a small event like download successful. To begin with, Android API has provided us with the AlertDialog.Builder with that only we are going to create our own dialog.

private fun showDialog(){
        val alertDialog = AlertDialog.Builder(this)
        alertDialog.apply {
            setTitle("Simple Dialog")
            setMessage("This is simple default dialog")
            setPositiveButton("OK",object :DialogInterface.OnClickListener{
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    dialog?.dismiss()
                }

            })

            setNegativeButton("Cancel") { dialog, which ->
                dialog?.cancel()
            }

            create()
        }

        alertDialog.show()
    }

By calling this function in a click event we will show the alert dialog, let's look into the code, we created an alert dialog. We start off with creating an AlertDialog.Builder which requires context as a parameter, then we apply the details on how our dialog should look and the characters along with the default buttons click listener, for this we use Kotlin apply scope function, We can create and show an empty dialog, but its good to have some content in that little popup. 

If you want a better understanding check out the sample screenshot on which item is which and how it's reflected in the application, First, we set a title for the dialog using the setTitle function with the title as a string in here its "Simple Dialog" then we follow the same for the message of the dialog setMessage("This is simple default dialog"), then we need to create a button so that the user can proceed with the dialog for that we use the predefined methods as we did for the title and message


We can provide up to three buttons Positive, Negative, and Neutral button, for this example, we used only the positive button and negative buttons, we named them OK and Canel button. the button creation methods are a little different from what we used to create the texts in the UI, along with the button name like "Ok" and "Cancel", in order for the button to be interactive, to make it clickable we need to prove an onClick callback provided by the DialogInterface.OnClickListener, inside the onClick call back we can access the dialog to do further operation or to dismiss the dialog once the user clicks either the "Ok" or "Cancel" button in the dialog.

alertdialog in android kotlin with Ok and Cancel button

After setting up the necessary thing to show in our dialog we call create() function in the builder to create the alert dialog then we will call show() function to display the little popup on the screen for the user to make a decision or complete an action.

How To Show An Android Dialog Fragment:

Now that we know how to create and show an alert dialog in android we can make it more interesting, lets say we wanted to achieve a different or a long functionality like uploading an image to the server and at the same time we don't want the user to proceed further, in these use case an alert dialog may look like a viable option but it will complicate the code, and its best to choose a dialog fragment for that., if you want to know more about fragments in android check here: How To Create Android Fragment With Kotlin  

Create a new Kotlin class file and name it as you want we named our file as "SimpleFragment.kt" my bad but keep in mind it's great if the name ends with DialogFragment instead of Fragment, then extend the class with DialogFragment() class. that's it, you have successfully created a dialog fragment, Just kidding, there is one more thing we need to do which is to create and show the dialog, since dialogs are popup screen they will not be visible unless called upon, and it is our responsibility to dismiss the dialog properly. To complete the implementation of the DialogFragment, we need to override the onCreateDialog function, which will return a Dialog, Refer to the code below
SimpleFragment.kt

  class SimpleDialogFragment : DialogFragment(){


    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return AlertDialog.Builder(requireContext()).apply {
            this.setTitle("Dialog Fragment")
            setMessage("This is Dialog Fragment, Do you want to close the dialog?")
            setPositiveButton("Yes"
            ) { dialog, _ -> dialog?.dismiss() }

            setNegativeButton("No"
            ) { dialog, _ -> dialog?.dismiss() }
        }.create()
    }

}
  
  
To simplify the tutorial we used the same code from our simple dialog example here with the values changed, this also shows how a dialog can be used for a different purpose, But the idea is the same since we want to return a dialog, we create a new android alert dialog with AlertDialog.Builder, and return it this time we only create the dialog, it's a different story for to show it which you can see the below code

private fun showDialogFragment() {
        val dialogFragment = SimpleDialogFragment()
        dialogFragment.show(supportFragmentManager,"DialogFragment")
    }

This is the function we call when we wanted to show our SimpleDialogFragment, usually, we call this function inside an onClick action. We create a new object for the SimpleDialogFragment, it doesn't have to be a new object every time you can save it globally and can reuse the same whenever you want, then at the time you want to show the dialog, call show function in the class we created for this show function is responsible for showing the dialog on the screen which intakes two parameters one is supportFragmentManager to make the fragment transaction and a  tag to identify the fragment.

android show dialog fragment with alertdilalog in kotlin

How To Show Custom AlertDialog In Android :

A custom alert dialog is something we create with a custom UI like adding an EditText to that little popup, the dialogs which are created with AlertDialog.Builder's will look like a static one because of its pre-defined options like title, message, and set buttons function to create and show, in which you cannot add an input EditText or an ImageView to it, for that if we want to get some information about the user like in an EditText we need to go with custom design, so start by creating a new layout, if you want to learn about complex UI design you can learn some advanced techniques about constrain layout, now once you have beautiful UI designed for our dialog, let's create and show it to the user.

    private fun showCustomDialog(){
        
        val alertDialog = AlertDialog.Builder(this).apply {
            setView(R.layout.custom_dialog_layout)
        }.create()

        alertDialog.show()
        alertDialog.findViewById<Button>(R.id.closeThisDialog)?.setOnClickListener {
            Log.d("Dialog","IS TRIGGERED")
            alertDialog.dismiss()
        }
        
    }
The is the function which we need to call when we want to show a custom alert dialog, the approach here is a little different, from AlertDialog.Builder, we create the dialog and store it to a variable, because we need to use that variable to do the further operation, and before creating we need to mention the layout which we designed earlier to the Builder using the setView method then we create the dialog.

Then we show the dialog, by calling show() on the alertDialog, now that its visible to the user, we need to define the user interactions, for example, if we have a button to close the dialog we need to define its implementation, and thus has to be only after the dialog is shown, now here we need to access the UI elements from the dialog object because it is the one that created those UI elements the buttons or anything it could be because if we simply call the findViewById here it will throw a java.lang.NullPointerException, the reason behind this is because here the dialog only knows the reference to its views so we need to only access the button or an EditText we should the dialog reference only, then the rest simple we can do all kind of operation we do to a normal View, also don't forget to call dismiss(). 

how to show custom layout in andorid alert dialog example code in kotlin

Additional Points When Working With Alert Dialogs:

Dialogs can be used for many use cases, so here are a few helpful points and the mistakes to avoid, when working with dialogs,
  •  Always make sure you call show(), I know little things are the things we often miss out on.
  • If you want to disable the close action on clicking outside of dialog use setCancelable(false)
  • If you want to know if your dialog is showing or not, you can use alertDialog.isShowing

Conclusion:

With this I conclude this post, I know AlertDialog is a large concept I tried my best to cover the common use case, this only gives a good overview about it, if you want to know anything in specific comment below or reach out to me, as we do it for all the post, this project is also shared in my Github profile you can pull the code from here: https://github.com/blackzshaik/AlertDialogAndroidExampl

Make sure to like our Facebook  
Follow Us Instagram 


Thanks For Reading!!! Sharing is caring,

keywords:

Post a Comment

0 Comments