【问题标题】:How to setup Data Binding in Android Studio?如何在 Android Studio 中设置数据绑定?
【发布时间】:2020-07-21 19:38:58
【问题描述】:

Data Binding 的 Android 开发人员指南包含以下代码,用于在应用模块的 build.gradle 文件中启用数据绑定:

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

但在添加此代码后,构建失败并出现此错误:

error: package androidx.databinding does not exist

Gradle 版本:4.0.1

语言:科特林

【问题讨论】:

标签: android kotlin build.gradle android-databinding


【解决方案1】:

设置数据绑定:

Build.gradle(:app)

dataBinding {
        enabled = true
    }

依赖关系

implementation 'com.android.databinding:compiler:3.5.1'

像这样在 xml 中绑定你的数据:

<?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 并清理和重建项目

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-17
    • 1970-01-01
    • 2020-05-04
    相关资源
    最近更新 更多