Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an AlertDialog in a fragment using Kotlin

Tags:

android

kotlin

In my Android app, I have an observer and in the callback I want to display an AlertDialog. The Builder method however needs a context. I need to obtain the context of the activity that the fragment is in but am not sure how to get it:

viewModel.onError.observe(this, Observer {
    val mAlertDialog = AlertDialog.Builder(activity) // This needs the activity's context
    mAlertDialog.setMessage(it.toString())
    mAlertDialog.show()
})
like image 775
Johann Avatar asked May 24 '19 07:05

Johann


People also ask

How do I show AlertDialog in Kotlin?

To set the action on alert dialog call the setPositiveButton(), setNeutralButton() and setNegativeButton() methods for positive, neutral and negative action respectively. The show() method of AlertDialog. Builder is used to display the alert dialog.

How do I use AlertDialog?

Alert Dialog code has three methods:setTitle() method for displaying the Alert Dialog box Title. setMessage() method for displaying the message. setIcon() method is used to set the icon on the Alert dialog box.

What is the difference between dialog and DialogFragment?

Dialog: A dialog is a small window that prompts the user to make a decision or enter additional information. DialogFragment: A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.


1 Answers

You should pass activity!! for Fragment.

val dialogBuilder = AlertDialog.Builder(activity!!)
        dialogBuilder.setMessage(it.toString())
                // if the dialog is cancelable
                .setCancelable(false)
                .setPositiveButton("Ok", DialogInterface.OnClickListener {
                    dialog, id ->
                    dialog.dismiss()

                })

        val alert = dialogBuilder.create()
        alert.setTitle("Test")
        alert.show()
like image 78
IntelliJ Amiya Avatar answered Sep 20 '22 21:09

IntelliJ Amiya