我意识到这是一个相当普通的错误消息,可能有一个简单的修复,但我遗漏了一些东西,可能需要另一双眼睛:
2020-09-25 17:09:29.006 ... E/AndroidRuntime: FATAL EXCEPTION: main
...
java.lang.ClassCastException: com.google.android.material.textview.MaterialTextView cannot be cast to com.google.android.material.textfield.TextInputEditText
at ...MessagesFragment$onViewCreated$1$$special$$inlined$apply$lambda$1.onClick(MessagesFragment.kt:171)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
我的片段中的相关代码:
fab.setOnClickListener {
MaterialAlertDialogBuilder(it.context).apply {
setView(R.layout.dialog_messages)
setPositiveButton("Add") { dialog, which ->
Log.d(TAG, "Message is ${message.text.toString()}!")
}
setNegativeButton("Remove") { dialog, which ->
}
setNeutralButton("Cancel", null)
}.show()
}
崩溃指向以下线路:
Log.d(TAG, "Message is ${message.text.toString()}!")
对话框布局/setView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/linearLayout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Message" >
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/message"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
感谢快速的线索棒!
问题源于使用kotlin的合成函数访问错误的视图。实际上,message
指的是另一个视图,而不是dialog_messages
内部的视图。
最简单的方法是首先扩展对话框的视图,以便能够访问其包含的视图(例如dialogView.message.text.toString()
(,然后使用setView(view: View)
函数而不是setView(layoutId: Int)
:
fab.setOnClickListener {
MaterialAlertDialogBuilder(it.context).apply {
val dialogView = LayoutInflater.from(it.context).inflate(R.layout.dialog_messages, null, false)
setView(dialogView)
setPositiveButton("Add") { dialog, which ->
Log.d(TAG, "Message is ${dialogView.message.text.toString()}!")
}
setNegativeButton("Remove") { dialog, which ->
}
setNeutralButton("Cancel", null)
}.show()
}