info@androidpaper.co.in

How to use Alert Dialog in Kotlin?

In Kotlin, you can use an AlertDialog to display a pop-up dialog with a message and optional buttons for user interaction. Here's a step-by-step guide on how to use AlertDialog in Kotlin:

Step 1: Add the necessary imports:

import android.app.AlertDialog
import android.content.Context

Step 2: Create a function to show the AlertDialog:

fun showAlertDialog(context: Context, title: String, message: String) {
    val alertDialogBuilder = AlertDialog.Builder(context)

    // Set the title and message for the AlertDialog
    alertDialogBuilder.setTitle(title)
    alertDialogBuilder.setMessage(message)

    // Set a positive button and its click listener (optional)
    alertDialogBuilder.setPositiveButton("OK") { dialog, which ->
        // You can add some action here if the user clicks the "OK" button
    Toast.makeText(getApplicationContext(),
                                    "Clicked on OK", Toast.LENGTH_SHORT)
                            .show();
    }

    // Set a negative button and its click listener (optional)
    alertDialogBuilder.setNegativeButton("Cancel") { dialog, which ->
        // You can add some action here if the user clicks the "Cancel" button
   Toast.makeText(getApplicationContext(),
                                    "Clicked on Cancel", Toast.LENGTH_SHORT)
                            .show();
    }

    // Create and show the AlertDialog
    val alertDialog = alertDialogBuilder.create()
    alertDialog.show()
}

Step 3: Call the function to display the AlertDialog:

// Example usage:
showAlertDialog(context, "Alert", "This is an example alert message.")

In the code above, the showAlertDialog function takes a Context (usually an activity or fragment context), a title, and a message as input parameters.
It creates an AlertDialog using the AlertDialog.Builder class, sets the title and message using setTitle and setMessage, and optionally adds positive and negative buttons with their respective click listeners.
Finally, the AlertDialog is created and displayed using the create() and show() methods, respectively.

Feel free to customize the showAlertDialog function based on your specific requirements, such as changing the button text or adding more buttons with different actions.