Data Binding 的 Android 开发者指南有以下代码可在应用程序模块的 build.gradle
文件中启用数据绑定(bind):
android {
...
buildFeatures {
dataBinding true
}
}
但是添加此代码后,构建失败并出现以下错误:
error: package androidx.databinding does not exist
Gradle 版本:4.0.1
语言:Kotlin
最佳答案
设置数据绑定(bind):
内部Build.gradle(:app)
dataBinding {
enabled = true
}
依赖关系
implementation 'com.android.databinding:compiler:3.5.1'
像这样在 xml 中绑定(bind)数据:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="item"
type="DataModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="@{item.name}"/>// binding data from model
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
了解更多详情:here
注意:同步 gradle 并清理和重建项目
关于android - 如何在 Android Studio 中设置数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63021915/