解决ButterKnife 8.1的依赖问题

新版本的ButterKnife的添加方式发生了变化,然后摸索着记录了一下:

按照ButterKnife的官网描述,使用ButterKnife需要在Gradle中添加如下依赖:

1
2
compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'

然而同步Gradle之后发现报了一个错:Gradle DSL method not found: 'apt()',然后在StackOverflow中找到了解决方法:

  • 需要在项目层级的gradle文件中添加classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8',即像下面那样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
  • 然后需要在app层级的gradle文件中添加apply plugin: 'com.neenbedankt.android-apt'。即像下面那样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'

android {
compileSdkVersion 24
buildToolsVersion "24.0.0"

defaultConfig {
applicationId "com.wl9739@foxmail.com.testgradle2"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.0.0'

compile 'com.jakewharton:butterknife:8.1.0'
apt 'com.jakewharton:butterknife-compiler:8.1.0'
}

最后,同步Gradle,你就可以愉快地使用ButterKnife了。

如果觉得文章对你有帮助,请我喝杯可乐吧