Alertdialog Listener Not Attached
MyAlertDialog throws ClassCastException when trying to set the context to the listener. I'm calling the MyAlertDailog from a fragment. I'm using the guide found in the android dev
Solution 1:
Even though the launchAlertDialog()
method is inside of MyFragment
, the "host" for MyAlertDialog
is your Activity, not MyFragment
.
Implement MyAlerDialog.MyAlertDialogListener
inside of MainActivity
in order for the cast to succeed. MainActivity can then communicate to MyFragment
if it has to.
Alternatively, you could use setTargetFragment()
in order to "connect" MyFragment and MyAlertDialog directly:
val dialog = MyAlertDialog()
dialog.setTargetFragment(this, 0)
dialog.show(requireActivity().supportFragmentManager, "DialogInfoFragment")
Then, rather than overriding onAttach()
and casting a context, you would cast the results of getTargetFragment()
:
builder.setPosiviveButton(
"Positive button",
DialogInterface.OnClickListener {
val listener = targetFragment as MyAlertDialogListener
listener.onDialogPositiveClick(this)
}
)
Post a Comment for "Alertdialog Listener Not Attached"