视图绑定适用于一种布局,但不适用于另一种布局

View Binding is working for one layout, but not working for another

android 开发的新手,我正在尝试应用视图绑定,因为它们是 Google 目前推荐的视图引用方法。我有两个布局 content_main.xml 和 content_note_list.xml。我得到了第一个 'content_main_xml' (MainActivity) 来使用 View Binding。但是我在实现第二个 'content_note_list.xml'.

的视图绑定时遇到了问题

下面是使应用程序在模拟器中不断崩溃的代码 here's the image of the code block

它在我不使用视图绑定时有效。

setContentView(R.layout.activity_note_list)

但是当我尝试使用视图绑定时,它打开应用程序并立即崩溃

setContentView(binding.root)

我不知道我做错了什么,我已经按照官方android开发网站提供的描述进行操作,多个视频。 任何帮助都是必要的。

编辑: content_note_list.xml activity_note_list.xml

为附加图像文件道歉,当我尝试附加它时,代码变得一团糟。

好像是这个名字。记得来自 android documentation。如果您的布局是 result_profile.xml

<LinearLayout ... >
    <TextView android:id="@+id/name" />
    <ImageView android:cropToPadding="true" />
    <Button android:id="@+id/button"
        android:background="@drawable/rounded_button" />
</LinearLayout>

ViewBinding 会生成ResultProfileBinding.

If view binding is enabled for a module, a binding class is generated for each XML layout file that the module contains. Each binding class contains references to the root view and all views that have an ID. The name of the binding class is generated by converting the name of the XML file to Pascal case and adding the word "Binding" to the end.

所以,考虑到这一点。如果您的布局是 activity_note_list,它将生成 ActivityNoteListBinding class 或类似的东西。在您的代码中,您正在设置 ContentNoteListBinding class。尝试用 ActivityNoteListBinding 替换 ContentNoteListBinding。另外,如果不能解决问题。尝试从控制台日志中添加代码。它有关于错误的更多详细信息。

更新

如果您想处理包含在 activity/fragment over <include> 标签中的 View 或 ViewGroup,您几乎可以直接访问这些视图。您需要在此标记中添加一个 Id <include>。然后您将可以访问这些组件:例如:

这是一个activity_note_list.xml

........
<include 
    id="+@id/ly_content_list_note"
    layout="@layout/content_list_note"/>
........

和content_note_list.xml

<listView
    id="+id/listNotes"
    .......
/>

现在在你的Activityclass中,你可以这样访问:

binding.lyContentListNote.listNotes

如您所见,首先直接访问容器的 ID,即 ly_content_list_note,然后是其中的所有视图组件,在本例中为 listNotes.

添加到@rguzman 的回答中,为了避免 运行 出现绑定类型意外设置错误的问题,您可以使用 DataBindingUtil 库。

对于Activity

val binding = DataBindingUtil.setContentView(this, R.layout.your_file)

对于片段

 binding = DataBindingUtil.inflate(inflater, R.layout.your_file, container, false)

//other logic

return binding.root

link 到官方文档了解更多信息