android - 如何在 Android Studio 中设置数据绑定(bind)?

标签 android kotlin build.gradle android-databinding

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/

相关文章:

android - SpannableString 和 TextAppearanceSpan,仅应用颜色

Android Jetpack compose - 观察第二次更改后未触发的实时数据

java - 如何比较 arraylist 与 kotlin 中的嵌套 arraylist?

android - 使用 LiveData 在 SeekBar 和 EditText 中取得进展

java - 依赖 org.json :json:20090211 is ignored for debug as it may be conflicting with the internal version provided by Android

java - 无法将“导出”识别为内部或外部命令,

中国、塞尔维亚和台湾不提供带应用内付费功能的 Android 免费应用

安卓:为什么是包裹?

java - 当在 AndroidSchedulers.mainThread() 上观察到 Observable 时,Android JUnit 测试无限期阻塞

android - 将 productFlavor 添加到实验性 Android gradle 插件库