Show Alert Dialog With an Input Field (EditText) in Android Kotlin

Today we are going to discuss how to show an alert dialog with an input field (EditText) in Android Kotlin. In this article, you will learn a lot about an AlertDialog.

Description

Actually Android doesn’t have the built-in dialog to do this. Fortunately, this is just a little extra work on top of creating a standard alert dialog box. All you need to do is create the Edit Text for the user to enter the data and configure it as a view of the alert dialog box. If required, you can customize the type of input allowed using setInputType, if you need.

If you can use the class member variable, you can just set the variable to the value for Edit Text. It remains unchanged after clearing the dialog box.

Show Alert Dialog With an Input Field

Within Your Class:

private String m_Text = "";

Where ever you want to show an alert dialog with input box, you can use the following method

Code

fun showdialog(){
        val builder: AlertDialog.Builder = android.app.AlertDialog.Builder(this)
        builder.setTitle("Title")

// Set up the input
        val input = EditText(this)
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
        input.setHint("Enter Text")
        input.inputType = InputType.TYPE_CLASS_TEXT
        builder.setView(input)

// Set up the buttons
        builder.setPositiveButton("OK", DialogInterface.OnClickListener { dialog, which ->
            // Here you get get input text from the Edittext
            var m_Text = input.text.toString()
        })
        builder.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which -> dialog.cancel() })

        builder.show()
    }

Press Alt + Enter to import AlertDialog and Builder in your Activity or Fragment. In the above code first, we have created a Builder object of type AlertDialog.Builder(). Then we just have to create the EditText object and assign it to the Builder. We can also set the positive or negative buttons in the dialog if required. Finally, call builder.show() method to show the dialog.

That’s It. This is how to show alert dialog with an input field in Android Kotlin

If you have any questions, feel free to ask in the comments section below.

Next Article

Get Full-Screen Size Including Status Bar & Navigation Bar – Android

Please share this post:
Posts created 31

Ask a Question

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: