ButterKnife-View注入架構(簡單介紹和在Studio中安裝)
1.簡單介紹
Butter Knife使用簡單介紹
作為一名Android開發,是不是經常厭煩了大量的findViewById以及setOnClickListener代碼,而ButterKnife是一個專注于Android系統的View注入架構,讓你從此從這些煩人臃腫的代碼中解脫出來。先來看一段代碼示例說明下ButterKnife是如何簡化代碼的:
注意:如果你是使用的Eclipse引用該library,你需要參考這裡Eclipse Configuration做一些配置,否則會運作出錯。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90TUNp3Yq5kerRUT4FEVkZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DN3YDM1ADNwEzNwITM2EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
而用ButterKnife之後的代碼是這樣的:
Butter Knife特性
- 支援 Activity 中的 View 注入
- 支援 View 中的 View 注入
- 支援 View 事件回調函數注入
目前支援如下事件回調函數:
- View: @OnLongClick and @OnFocusChanged.
- TextView: @OnEditorAction.
- AdapterView: @OnItemClick and @OnItemLongClick.
- CompoundButton: @OnCheckedChanged.
下面來看一些注入的示例代碼:
在Activity 中注入
在Fragment中注入
在ViewHolder中注入
注入回調函數
下面是幾種注入回調函數的方法示例:
Reset函數
如果需要在 界面 銷毀的時候,把注入的 View 設定為 Null, 則可以用 reset 函數:
另外 還支援 可選的 View 注入,如果該 View 沒有,就沒有吧:
還有兩個 findViewById 函數來簡化查找 View 的方式,如果上面都滿足不了你的需求,你可以用用他們:
如果你是用Studio開發的,在Studio中安裝Butter Knife插件簡單介紹如下:
2.插件安裝
1.本人使用的是studio2.0,在點選File—>Settings—>Plugins如下:
2.點選上圖紅圈處選項,在搜尋框中輸入Zelezny,如果沒有安裝右上角會提示你安裝(我的是已經安裝過的!),安裝後會提示重新開機Studio,重新開機即可
3.Butter Knife使用
1.在bulid.gradle中添加依賴
重新編譯一下該項目,通過後繼續操作。
2.具體使用(對于這樣的xml檔案)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_veiw_tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView 1" />
<Button
android:id="@+id/button_bt1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
<TextView
android:id="@+id/text_veiw_tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView 2" />
<Button
android:id="@+id/button_bt2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
在對應的Java類中的布局處—>右鍵
在對應的View中形成的标注如下
參考文檔:
http://stormzhang.com/openandroid/android/2014/01/12/android-butterknife/
http://blog.csdn.net/cxc19890214/article/details/47430547