为什么我找不到片段布局中包含的布局的子级 ViewById?



我在xml中包含了一个片段的布局。在片段的Kotlin代码中,我想访问布局中的一个按钮,以便设置其onClick侦听器。但是,尝试按id查找按钮会导致应用程序关闭。(我使用底部导航导航到片段,应用程序就关闭了。没有错误消息。(按id查找布局本身是成功的,因为将其记录为字符串会给出"androidx.constraintlayout.widget.constraintlayout…",这是我包含的布局的父标记。

这是我的简化代码:

包含的布局,noteView.xml:

...
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/noteViewCont">
<ImageButton
android:id="@+id/button"/>
...

fragment.xml布局:

...
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frameLayout">
<FrameLayout
...>
<include
android:id="@+id/noteViewCont"
layout="@layout/noteview"
.../>
<FrameLayout/>
...

(虽然我没有在那里写,但FrameLayout和ImageButton有限制(

我的碎片.kt:

...
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment, container, false)
val noteVw: View = root.findViewById(R.id.noteViewCont)
Log.v("test", noteVw.toString())
...
val btn: Button = noteVw.findViewById(R.id.button)
...
return root
}

我提到了这个问题,并尝试了那里提出的各种解决方案:findViewById不适用于include?没有一个奏效。-正如您所看到的,包含的XML文件的id与include(noteViewCont(的id相同。-我尝试在onViewCreated((中设置noteVw,但没有任何改变。

谢谢!

更新

-我尝试了一个建议,基本上完全绕过noteVw,做root.findViewById(R.id.button),但这没有改变

此外,这是我尝试过的onViewCreated:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val noteVw: View = view.findViewById(R.id.noteViewCont)
val makeBtn: Button = noteVw.findViewById(R.id.button)
}

第二次更新

多亏了@CôngH,我明白了ải.有一次他要求提供崩溃日志,我意识到在我一直说应用程序"没有错误消息"之前,我可能应该检查一下我是否收到了崩溃日志。所以,我找到了这篇文章https://www.loginworks.com/blogs/get-crash-logs-android-applications/在我的崩溃日志中发现了这个:

05-04 01:17:43.758   551   551 E AndroidRuntime: java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageButton cannot be cast to android.widget.Button

我在这篇文章中没有包括的一个细节是,我实际上正在为我试图存储在val button: Button中的视图使用ImageButton。我把Button换成了ImageButton,一切都很好。此外,第一个变化@CôngHả我建议是简化代码的好方法。你可以直接从包含它的布局中访问包含布局的子级。我删除了noteVw,只使用root.findViewById来获取按钮。很抱歉提出了一个明显的问题,但我希望这是一个有用的例子。

在XML中,您定义了ImageButton,但在代码中,您将其强制转换为Button,而不是Button的实例,更改为

val makeBtn: ImageButton = noteVw.findViewById(R.id.button)

最新更新