我想使用 ObservableList,所以我关注 this instruction ,在我的 (Module:app)build.gradle 和 Syns 上添加以下代码:
android {
...
buildFeatures {
dataBinding true
}
}
是的,它有效。我现在可以将 ObservableList 导入我的类(class)。但问题是,当我运行应用程序时,会发生编译异常(NullPointException):<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="0dp">
<com.example.lj032.myapplication.MyGridView
android:id="@+id/grid_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/LinearLayout1"
android:numColumns="4"
android:layout_alignParentStart="true" />
</RelativeLayout>
根据日志,显然问题是由数据绑定(bind)库引起的。但我不知道如何解决这个问题。
最佳答案
How can I properly Enable dataBinding
内部
Build.gradle(:app)
dataBinding {
enabled = true
}
依赖项:implementation 'com.android.databinding:compiler:3.5.1'
像这样绑定(bind)你的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>
P.S:不要忘记在 Build.gradle(:app)
中添加插件apply plugin: 'kotlin-kapt'
完成上述所有步骤同步和重建项目后
关于android - 如何在我的 android 项目中正确启用 android.databinding 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63097492/