Data Binding class 不会自动生成,原因是因为layout里面没有设置Layout 标签
修改前:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".guesstheword.title.GuessTitleFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
修改后:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".guesstheword.title.GuessTitleFragment">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />
</FrameLayout>
</layout>
总结
启用Data Binding 需要检查以下3点
- 检查data-binding 是否开启
需要在 build.gradle 文件里面配置 data binding 属性,如果没有刚需要添加,并且点击 Sync 来同步
android {
...
buildFeatures {
dataBinding true
}
}
- 检查layout 文件是否有添加layout 标签
如果想要转换成Data binding class 来自动生成DataBinding 文件,需要添加layout 标签,如下
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.constraint.ConstraintLayout>
</layout>
Along with this check whether the binding variable names are correct as in the view model class
- 自动生成Binding class 名字 ?
这个时候data binding class应该就会自动生成,自动被创建。
如果layout 的名字是activity_main.xml,那么 data binding class 将会被自动生成 ActivityMainBinding
另外如果需要使用Data bindding ,需要将Android studio 升级到 Android Studio 3.2, 或者更高。
参考连接:Data Binding class not generated