报错代码: BR类没找到
e D:\study\DemoKt\app\src\main\java\com\example\lanidemokt\viewmodel\OrderViewModel.kt: (19, 22): Type mismatch: inferred type is () -> Unit but Unit was expected
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
class OrderViewModel: BaseObservable() {
@get:Bindable
var REFNO: String? = null
set(value) = {
field = value
notifyPropertyChanged(BR.REFNO)
}
}
分析:build.gradle(:app)引入kapt
plugins{
id 'kotlin-kapt' }android
buildFeatures { viewBinding true compose true } dataBinding { enabled = true } kapt { generateStubs = true } }dependencies{
kapt "androidx.room:room-compiler:2.4.0" }
完整build.gradle
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.jetbrains.kotlin.android)
id 'kotlin-kapt'
}
android {
namespace 'com.example.lanidemokt'
compileSdk 31
defaultConfig {
applicationId "com.example.lanidemokt"
minSdk 24
targetSdk 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
lintOptions {
abortOnError false
}
buildFeatures {
viewBinding true
dataBinding true
compose true
}
dataBinding {
enabled = true
}
kapt {
generateStubs = true
}
}
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.2"
implementation "androidx.compose.ui:ui:1.0.1"
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'androidx.appcompat:appcompat-resources:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.compose.material:material:1.0.1'
implementation 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
kapt "com.android.databinding:compiler:7.5.0"
}
解决:
手动引入 手写当前包名:import com.example.lanidemokt.之后就显示BR出来。
alt +enter引入不了
引入BR之后的报错:
BR Required:UnitFound:() → Unit
set(REFNO) = {
这里多了个等号,新手爱犯错。
最终代码
set(REFNO) {} 不要使用全部大写,REFNO编译到BR.java是 rEFNO
notifyPropertyChanged(BR.REFNO) 这里会出错: Unresolved reference: REFNO
package com.example.lanidemokt.viewmodel
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import com.example.lanidemokt.BR
class OrderViewModel: BaseObservable() {
/*
BR 类生成位置在 //app\build\generated\source\kapt\debug\com\example\lanidemokt
* */
@get:Bindable
var refno: String? = null
set(refno) {
field = refno
notifyPropertyChanged(BR.refno)
}
}
总结:
有点乱,新手上路,各种踩坑,加油吧。