此文章來自http://www.jianshu.com/p/fe3c20f3ac27點擊打開鏈接
Android Studio中ButterKnife插件的安裝與使用
最近用到Android Butterknife Zelezny插件,感覺特別棒!在Android開發過程中,我們會寫大量的初始化控件和設置控件點擊事件的操作,這樣簡單而重複的工作讓人覺得麻煩而且沒意思,可以採用註解的方式去實現,而ButterKnife是註解中相對簡單易懂的開源框架。
一、Android Studio中安裝ButterKnife插件:
(1)和安裝其他插件一樣,首先,打開:settings->plugins界面
(2)重新啓動了Android Studio之後,此時我們已經安裝了ButterKnife插件了,接下來在項目的bulid.gradle中添加依賴,如下圖所示:
compile 'com.jakewharton:butterknife:7.0.0'
(3)重新編譯一下該項目,就可以在代碼中使用註解的方式了,在這裏我們先寫一個簡單的佈局文件來舉例:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView1" />
<Button
android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />
<ImageView
android:id="@+id/iv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
</LinearLayout>
如果不使用ButterKnife插件,我們需要在 重寫的onCreate()方法中通過findViewById()對控件進行實例化並對控件添加事件監聽,如下如所示:
代碼還是比較簡潔,這也是因爲我們的佈局相對而言比較簡單,可是如果佈局比較複雜的話,這樣的操作就顯得比較繁瑣。現在我們只需要簡單點擊幾下鼠標就可以完成這些操作了。
(4)鼠標雙擊選擇佈局文件名,右鍵(或者直接快捷鍵:Alt+Insert)