【发布时间】:2020-12-02 21:41:32
【问题描述】:
MyAlertDialog 在尝试为侦听器设置上下文时抛出 ClassCastException。我正在从片段中调用 MyAlertDailog。
我正在使用 android 开发文档中的指南。
https://developer.android.com/guide/topics/ui/dialogs#PassingEvents
我的片段
class MyFragment : Fragment(), MyAlerDialog.MyAlertDialogListener {
...
fun launchAlertDialog() {
val dailog = MyAlertDialog().also {
it.show(requireActivity().supportFragmentManager, "DialogInfoFragment")
}
}
override fun onDialogPostiveCLick(dialog: DialogFragment) {
Log.i(TAG, "Listener returns a postive click")
}
}
我的警报对话框
class MyAlertDialog : DialogFragment() {
// Use thsi instance for the interface
internal var listener: MyAlertDialogListener
// My Fragment implements this interface.
interface MyAlertDialogListener {
onDialogPositiveClick(dialog: DialogFragment)
}
override fun onAttach(context: Context) {
super.onAttach(context)
// Verify that the host implements the callback.
try {
// My problem is here.
listener = context as MyAlertDailog
} catch (e: ClassCastException) {
// exception thrown here.
throw ClassCastException((context.toString() + " must implement MyAlertDailogListener")
}
}
override fun onCreateDialog(savedInstanceState:Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.builder(it)
...
builder.setPosiviveButton("Positive button",
DialogInterface.OnClickListener {
listener.onDialogPositiveClick(this)
}
}
}
}
错误报告
java.lang.ClassCastException: com.example.androiddevpractice.MainActivity@ab56136 must implement MyAlertDialogListener
at com.example.androiddevpractice.topics.userinterface.dialog.MyAlertDialog.onAttach(MyAlertDialog.kt:35)
【问题讨论】:
标签: kotlin android-alertdialog