Android Studio 3.1 beta中DataBinding与kapt编译报错求助
解决Android Studio 3.1 Beta中kapt()方法找不到的编译错误
我之前尝试用上Android Studio 3.1里「可在数据绑定表达式中将LiveData对象用作可观察字段」的新特性,结果下载3.1 Beta版本后项目直接编译失败,报了这个错:
Could not find method kapt() for arguments [com.android.databinding:compiler:2.3.0] on project ':app' of type org.gradle.api.Project
先贴一下我的顶层gradle配置:
// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { ext.kotlin_version = '1.2.30' ext.google_ver = '27.1.0' ext.google_play_ver = '11.8.0' ext.retrofit_ver = '2.3.0' ext.arch_components_ver = '1.1.1' repositories { jcenter() google() maven { url "https://kotlin.bintray.com/kotlinx" } mavenLocal() } dependencies { classpath 'com.android.tools.build:gradle:3.2.0-alpha07' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version" classpath 'com.google.gms:google-services:3.1.2' } } allprojects { repositories { jcenter() mavenCentral() maven { url "https://jitpack.io" } maven { url "https://maven.google.com" } maven { url "https://kotlin.bintray.com/kotlinx" } google() flatDir { dirs 'libs' } } } task clean(type: Delete) { delete rootProject.buildDir }
问题原因&解决方案
这个报错主要有两个原因:一是没启用Kotlin的注解处理器插件,二是手动指定了过时的Data Binding编译器依赖,和你用的新版AGP不兼容。按下面的步骤改:
在模块的build.gradle中启用kotlin-kapt插件
打开app/build.gradle,在开头的插件声明里加上这一行:apply plugin: 'kotlin-kapt'只有应用了这个插件,你的模块才能识别
kapt()方法,它是Kotlin用来处理注解处理器的工具。移除手动添加的Data Binding编译器依赖
你应该在app/build.gradle里写了类似这样的代码:kapt 'com.android.databinding:compiler:2.3.0'从Android Gradle Plugin 3.0版本开始,不需要手动指定这个依赖了——AGP会自动根据你的插件版本匹配对应的Data Binding编译器版本。你指定的2.3.0版本太老,和当前用的3.2.0-alpha07 AGP完全不兼容,直接删掉这一行就行。
确保Data Binding已开启
还是在app/build.gradle的android块里,确认数据绑定是启用状态:android { // 其他配置... dataBinding { enabled = true } }
做完这些后,同步一下Gradle,重新编译项目应该就能解决这个问题了。
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

