注:本文的 Android Studio 版本為 2.1.2 。Butterknife的版本為8.2.1。如有操作差異,可能是版本差異。
Butterknife 是 Android Studio 的一個(gè)快速開發(fā)的插件,可以簡(jiǎn)化輸入控件初始化的過(guò)程(即減少控件的findViewById()代碼)。
一、下載插件
1.單擊菜單欄的 File,選擇 Setting;
2.在 Setting 對(duì)話框中選擇 Plugins;
3.在中間的搜索框中輸入 Butterknife,如果搜索不到,說(shuō)明該控件沒(méi)有被安裝過(guò),并且不在常用插件列表里,沒(méi)關(guān)系,可以點(diǎn)擊中間欄的下部選擇 Browse repositories... 這是從瀏覽器中搜索所需要的插件(在Android Studio 內(nèi)部)
4.在 Browse Repositories 對(duì)話框中輸入 Butterknife,在列表中選擇 Android Butterknife Zelezny ,點(diǎn)擊 Install 安裝,然后重啟 Android Studio ,就安裝好了。



二、在項(xiàng)目中配置
打開項(xiàng)目的 build.gradle 文件
首先在 dependencies 中添加 相應(yīng)的引用
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
compile 'com.jakewharton:butterknife:8.2.1'
apt 'com.jakewharton:butterknife-compiler:8.2.1'}
解決方法:
在.gradle 文件中添加
最后重新配置清單文件,操作如下:

三、使用
準(zhǔn)備工作到此就做好的,Butterknife的使用很簡(jiǎn)單
1.光標(biāo)放在相應(yīng) Activity 的布局文件上,按下 Alt+Insert,選擇 Generate Butterknife Injections
2.在彈出的對(duì)話框中,選擇你所需要的控件,然后選擇 Confirm 。



我們現(xiàn)在就可以直接對(duì)控件添加監(jiān)聽事件,賦值等操作。在以后的項(xiàng)目中使用,只需在項(xiàng)目的 build.gradle 文件中配置好就可以使用了。很方便的。
四、可能出現(xiàn)的錯(cuò)誤
1.沒(méi)有在 build.gradle 文件的上部添加
apply plugin: 'com.neenbedankt.android-apt'

Error:(29, 0) Gradle DSL method not found: 'apt()'
Possible causes:<ul><li>The project 'MyApplicationDemo' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin.
Apply Gradle plugin</li>
2.沒(méi)有添加build.gradle 文件添加
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}

Error:(2, 0) Plugin with id 'com.neenbedankt.android-apt' not found.
Open File