解决Kotlin和DataBinding冲突 Unresolved reference: databinding

在同时使用Kotlin和DataBinding的时候,会出现如下错误

E:\VersionManager\Demo\myclient\HopeHaloClientSampleKotlin\app\src\main\java\com\ethanco\hopehaloclientsample\SecondActivity.kt
Error:(6, 41) Unresolved reference: databinding
Error:(17, 26) Unresolved reference: ActivityMainBinding
Error:Execution failed for task ':app:compileDebugKotlin'.
> Compilation error. See log for more details  

或者是这个错误

Error:Execution failed for task ':app:compileReleaseJavaWithJavac'.
> java.lang.annotation.IncompleteAnnotationException: android.databinding.BindingBuildInfo missing element enableDebugLogs

解决办法

在app build.gradle中添加如下代码即可解决

kapt {
    generateStubs = true
}  

dependencies {
	//...
	//Android Studio3.0以后不需要一下这行代码
	//kapt "com.android.databinding:compiler:2.3.0"
}

完整配置

kotlin和databinding的完整配置如下

project的build.gradle

buildscript {
    ext.kotlin_version = '1.1.0'
    ext.android_plugin_version = '2.3.0'
    
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        //classpath "com.android.tools.build:gradle:$android_plugin_version"
    }
}  

app的build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'  
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'

android {
    //...
    dataBinding {
        enabled true
    }
    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }
}

kapt {
    generateStubs = true
}  

dependencies {
	//...
	compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
	//Android Studio3.0以后不需要一下这行代码
	//kapt "com.android.databinding:compiler:$android_plugin_version"
}

其他

详见 http://stackoverflow.com/questions/33165324/kotlin-android-unresolved-reference-databinding

你可能感兴趣的:(Android)