Android Studio 使用 插件 Butterknife

注:本文的 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 ,就安裝好了。

第一步.png
第二、三步.png
第四步.png

二、在項(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 文件中添加

最后重新配置清單文件,操作如下:


重新配置清單文件.png

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

1.png
2.png
結(jié)果.png

我們現(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'
錯(cuò)誤提示1.png

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'    
  }
}
錯(cuò)誤提示2.png

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容