Custom dialog android kotlin

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.

    Читайте также:  Функция xor python 3

    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:

    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, "$ 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() 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() 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(R.id.btDismissCustomDialog) btDismiss.setOnClickListener < customDialog.dismiss() >>

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

    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 $", 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:

    Be sure to check my other cool posts here about:

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

    Share this:

    Источник

    Kotlin Custom Dialog With Image and Title, Close and Two Buttons

    kotlin sqlite multiple tables, kotlin recyclerview checkbox, kotlin recyclerview button, kotlin load html javascript, kotlin recyclerview searchview, kotlin recyclerview search using edittext, kotlin listview with edittext, kotlin recyclerview with edittext, kotlin swipe to delete listview, kotlin recyclerview swipe to delete, kotlin expandablelistview with checkbox, kotlin custom ratingbar, kotlin change tab, Kotlin Select Multiple Images From Gallery, Kotlin Custom Dialog With Image And Title, kotlin select multiple video

    Let us make Kotlin Custom Dialog With Image and Title example.

    This custom dialog will also have two buttons like Ok and Cancel.

    We will also add the image in our custom dialog using Kotlin language.

    In this example, we will create one specific layout file where you can customize your pop up dialog.

    We will make a custom dialog in such a way that you will be able to add any UI widget like Text View, Edit Text, Button etc.

    A separate XML file will be there for the layout of dialog so that we can add any UI widget we desire.

    First of all, focus on the following video.

    Step 1. Inserting Image

    Make a new project in the android studio with empty activity as the default one.

    Also you need to set the Kotlin as the core language of the project.

    Now let us add the image in the dialog. For this, you need to add the image in the project.

    Click on the below link to download the image.

    After downloading the above image, app->res->drawable directory.

    Step 2. Writing Button Drawable Files

    Navigate to app->res->drawable directory. Make a new file called button.xml

    You should write the following in button.xml file.

    This file will create the attractive background for the button.

    For this, it is using three types of colors. These colors will create the gradient effect for the background.

    Now in the same directory, make another file and give it a name like button_yellow.xml

    Below is the code block for the button_yellow.xml

    This file is also used for the button background creation but this file have used different colors than the previous one.

    Step 3. Dialog XML File

    Go to app->res->layout directory. Here, create a new file with the name as dialog_layout.xml

    Now copy the following lines in dialog_layout.xml file.

    This file has one image view, one text view and two buttons.

    We will set that image in the image view which we have downloaded in the step 1.

    Text view will hold some text and we will be able to customize it from the Kotlin file.

    Ok and Cancel are the two buttons and we will control their on click event from Kotlin class.

    Step 4. Final and Main Text

    There are two main files in your android studio project : activity_main.xml and MainActivity.kt

    Following is the source snippet for activity_main.xml file.

    There is just one button in the above file. Compiler will open the custom dialog when the user clicks the button.

    Open your MainActivity.kt file and write down the below lines in this file.

    import android.app.Activity import android.app.Dialog import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.view.Window import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() < private var btn1: Button? = null override fun onCreate(savedInstanceState: Bundle?) < super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn1 = findViewById(R.id.btn1_d) btn1. setOnClickListener < showDialog(this@MainActivity, "First Custom Dialog") >> fun showDialog(activity: Activity, msg: String) < val dialog = Dialog(activity) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setCancelable(false) dialog.setContentView(R.layout.dialog_layout) val text = dialog.findViewById(R.id.text_dialog) as TextView text.text = msg val dialogButton1 = dialog.findViewById(R.id.btn1) as Button dialogButton1.setOnClickListener < dialog.dismiss() >val dialogButton2 = dialog.findViewById(R.id.btn2) as Button dialogButton2.setOnClickListener < dialog.dismiss() >dialog.show() > >

    First of all,compiler will create the object of the button. Then it will initialize it using it’s ID.

    After this, on click event of button is written.

    When the user clicks the button, compiler will call showDialog() method.

    Below is the coding lines for showDialog() method.

    fun showDialog(activity: Activity, msg: String) < val dialog = Dialog(activity) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.setCancelable(false) dialog.setContentView(R.layout.dialog_layout) val text = dialog.findViewById(R.id.text_dialog) as TextView text.text = msg val dialogButton1 = dialog.findViewById(R.id.btn1) as Button dialogButton1.setOnClickListener < dialog.dismiss() >val dialogButton2 = dialog.findViewById(R.id.btn2) as Button dialogButton2.setOnClickListener < dialog.dismiss() >dialog.show() >

    Compiler will first create the object of the Dialog class. Then it will set false in the setCancelable() method.

    It means that user will not be able to remove dialog by tapping on blank screen part around the dialog.

    After this, set the layout of the custom dialog. For this, it will use dialog_layout.xml file.

    So by doing this, we can access the text view and buttons which we have inserted in the dialog_layout.xml file.

    Now compiler will set the text in the text view.

    For this, it uses the string that it has received from the second parameter of showDialog() method.

    Finally, compiler will access two buttons of the dialog and it will write the click event for both of them.

    On the click event of both the buttons, compiler will simply dismiss the custom dialog.

    Источник

    Оцените статью