注:本文的 Android Studio 版本為 2.1.2 馍惹。Butterknife的版本為8.2.1搏色。如有操作差異,可能是版本差異缭召。
Butterknife 是 Android Studio 的一個快速開發(fā)的插件员辩,可以簡化輸入控件初始化的過程(即減少控件的findViewById()代碼)盒粮。
一、下載插件
1.單擊菜單欄的 File奠滑,選擇 Setting丹皱;
2.在 Setting 對話框中選擇 Plugins;
3.在中間的搜索框中輸入 Butterknife宋税,如果搜索不到摊崭,說明該控件沒有被安裝過,并且不在常用插件列表里杰赛,沒關系呢簸,可以點擊中間欄的下部選擇 Browse repositories... 這是從瀏覽器中搜索所需要的插件(在Android Studio 內(nèi)部)
4.在 Browse Repositories 對話框中輸入 Butterknife,在列表中選擇 Android Butterknife Zelezny ,點擊 Install 安裝乏屯,然后重啟 Android Studio 阔墩,就安裝好了。
二、在項目中配置
打開項目的 build.gradle 文件
首先在 dependencies 中添加 相應的引用
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 文件中添加
最后重新配置清單文件耸彪,操作如下:
三伞芹、使用
準備工作到此就做好的,Butterknife的使用很簡單
1.光標放在相應 Activity 的布局文件上,按下 Alt+Insert唱较,選擇 Generate Butterknife Injections
2.在彈出的對話框中扎唾,選擇你所需要的控件,然后選擇 Confirm 南缓。
我們現(xiàn)在就可以直接對控件添加監(jiān)聽事件胸遇,賦值等操作。在以后的項目中使用汉形,只需在項目的 build.gradle 文件中配置好就可以使用了纸镊。很方便的。
四概疆、可能出現(xiàn)的錯誤
1.沒有在 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.沒有添加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