How does one handle button clicks in a Dialog fragment. I would like to run method in fragment once a dialog button is clicked, the example given in dev docs works for activities but not fragments.
MyAlertDialog
class MyAlertDialog : DialogFragment() {
var listener: MyListener
interface MyListener {
onPositiveClick(dialog: DialogFragment)
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = context as MyListener
} catch (e: ClassCastException) {
throw ClassCastException((context.toString() + " must implement MyDailogListener")
}
}
override fun onCreateDialog(savedInstanceState:Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setMessage("Do you want to reset the score.")
.setPositiveButton("Confirm",
DialogInterface.OnClickListener { dialog, id ->
...
})
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
}
MyFragment
class MyFragment : Fragment(), MyAlertDialog.MyListener {
...
fun launchAlertDialog() {
val dailog = MyAlertDialog().also {
it.show(requireActivity().supportFragmentManager, "DialogInfoFragment")
}
}
override fun onDialogPostiveCLick(dialog: DialogFragment) {
Log.i(TAG, "Listener returns a postive click")
}
}