val dataBinding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
报错一:
Unresolved reference: ActivityMainBinding
首先你要知道一个概念,ActivityMainBinding是DataBinding中的一种视频绑定,通过activity_main.xml和此文件对应,即activity_main.xml会对应生成文件ActicityMainBinding.java文件,既然是视图绑定,就要看下你的配置文件是否写对了?
- android {
- ...
- buildFeatures {
- //这个引用,可以引入DataBindingUtil类
- //功能:数据绑定!
- dataBinding = true
-
- //这个引入,才能引入ActivityMainBinding (这个才是视图绑定!!!)
- //功能:视图绑定!
- //没有视图绑定,是不会自动编译生成ActivityMainBinding.java类的
- viewBinding = true
- }
- }
报错二:
val dataBinding = DataBindingUtil.setContentView<ActivityMainBinding>(this,R.layout.activity_main)
下划线位置报错:
Type argument is not within its bounds.
Expected:
ViewDataBinding!
Found:
ActivityMainBinding!
意思是:本来系统想要的是ViewDataBinding类,你给我的是ActivityMainBinding类。故,你要在activity_main.xml布局文件的根儿上添加
- "1.0" encoding="utf-8"?>
- <layout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools">
-
- <androidx.constraintlayout.widget.ConstraintLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity">
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World!"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintEnd_toEndOf="parent"
- app:layout_constraintStart_toStartOf="parent"
- app:layout_constraintTop_toTopOf="parent" />
-
- androidx.constraintlayout.widget.ConstraintLayout>
-
-
- layout>