首页 > 解决方案 > 即使我在 build.gradle 中启用了 dataBinding 构建选项,我的 android 工作室也无法识别 ActivityMainBinding 类

问题描述

我已添加到我的构建脚本中

 buildFeatures {
    dataBinding true
}

但是当我想使用 Binding 类时,它无法识别。我尝试过清理和重建,但它不起作用。我尝试制作新的 xml 文件并尝试为它们创建绑定实例,但没有任何效果。我是否错过了一些依赖,或者发生了什么?谢谢!

标签: androidandroid-studiodata-binding

解决方案


您正在使用数据绑定,它将整个布局文件与活动、片段和适配器绑定,它不会自动生成,您必须通过添加明确告诉 Android Studio(我不知道是谁在幕后做所有这些事情) XML 文件中的这个标签。

<layout 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 Studio 为这个布局生成绑定文件,因为如果我们有一个非常大的项目,通常我们不想为所有布局生成绑定文件,因为它会增加构建时间。

您可以使用此标签下的任何布局,例如,

<layout 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">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/backgroundColor"
    tools:context=".presentation.ui.activity.FullImageViewActivity">

    </androidx.constraintlayout.widget.ConstraintLayout>
  </layout>

记住布局标签只是告诉 Android Studio 是的,我们要为此布局生成绑定文件,但这不会是您的根视图,例如,

binding.root  

在我的情况下将参考Contraint Layout。


推荐阅读