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()
})
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With