Android中ButterKnife的詳細使用

最近剛學會使用ButterKnife,真是超級好用,忍不住要分享給大家了。

寫在前面:該文檔使用7.0版本,8.0版本方法名有所改動,建議看官方文檔,整體業務邏輯和原理沒什麼變動。

Android編程過程中,我們會寫大量的佈局和點擊事件,像初始view、設置view監聽這樣簡單而重複的操作讓人覺得麻煩類,所以可以採用註解的方式去實現,而ButterKnife則是註解中相對簡單易懂的很不錯的開源框架,而網上的文檔和例子都過時了,7.0之後的版本改動很大,之前的註解都不能用了,所以借鑑官方文檔總結了一下,接下來就介紹一下如何使用。基本參照官方文檔,加上自己的心得。


ButterKnife 優勢:

1.強大的View綁定和Click事件處理功能,簡化代碼,提升開發效率

2.方便的處理Adapter裏的ViewHolder綁定問題

3.運行時不會影響APP效率,使用配置方便

4.代碼清晰,可讀性強


使用心得:

1.Activity ButterKnife.bind(this);必須在setContentView();之後,且父類bind綁定後,子類不需要再bind

2.Fragment ButterKnife.bind(this, mRootView);

3.屬性佈局不能用private or static 修飾,否則會報錯

4.setContentView()不能通過註解實現。(其他的有些註解框架可以)


官網http://jakewharton.github.io/butterknife/

使用步驟:

一.導入ButterKnife jar包:

1)如果你是Eclipse,可以去官網下載jar包
2)如果你是AndroidStudio可以直接 File->Project Structure->Dependencies->Library dependency 搜索butterknife即可,第一個就是
3)當然也可以用maven和gradle配置

[html] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">MAVEN    
  2.     <dependency>    
  3.       <groupId>com.jakewharton</groupId>    
  4.       <artifactId>butterknife</artifactId>    
  5.       <version>(insert latest version)</version>    
  6.     </dependency>    
  7.     
  8. GRADLE    
  9. compile 'com.jakewharton:butterknife:(insert latest version)'    
  10.     
  11. Be sure to suppress this lint warning in your build.gradle.(關閉)    
  12. lintOptions {    
  13.   disable 'InvalidPackage'    
  14. }  </span>  

   


注意如果在Library 項目中使用要按如下步驟(github中有具體描述)否則無法找到view:


注:官網github也有對應的引用步驟。


二.常見使用方法:
1)由於每次都要在Activity中的onCreate綁定Activity,所以個人建議寫一個BaseActivity完成綁定,子類繼承即可
     注:ButterKnife.bind(this);綁定Activity 必須在setContentView之後:
     實現如下(FragmentActivity 實現一樣):

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">public abstract class BaseActivity extends Activity {    
  2.     public abstract int getContentViewId();    
  3.     
  4.     @Override    
  5.     protected void onCreate(Bundle savedInstanceState) {    
  6.         super.onCreate(savedInstanceState);    
  7.         setContentView(getContentViewId());    
  8.         ButterKnife.bind(this);    
  9.         initAllMembersView(savedInstanceState);    
  10.     }    
  11.     
  12.     protected abstract void initAllMembersView(Bundle savedInstanceState);    
  13.     
  14.     @Override    
  15.     protected void onDestroy() {    
  16.         super.onDestroy();    
  17.         ButterKnife.unbind(this);//解除綁定,官方文檔只對fragment做了解綁    
  18.     }    
  19. }  </span>  


2)綁定fragment
[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">public abstract class BaseFragment extends Fragment {    
  2.     public abstract int getContentViewId();    
  3.     protected Context context;    
  4.     protected View mRootView;    
  5.     
  6.     @Nullable    
  7.     @Override    
  8.     public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {    
  9.         mRootView =inflater.inflate(getContentViewId(),container,false);    
  10.         ButterKnife.bind(this,mRootView);//綁定framgent    
  11.         this.context = getActivity();    
  12.         initAllMembersView(savedInstanceState);    
  13.         return mRootView;    
  14.     }    
  15.     
  16.     protected abstract void initAllMembersView(Bundle savedInstanceState);    
  17.     
  18.     @Override    
  19.     public void onDestroyView() {    
  20.         super.onDestroyView();    
  21.         ButterKnife.unbind(this);//解綁    
  22.     }    
  23. }  </span>  

3)綁定view

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@Bind(R.id.hello_world)    
  2. TextView mHelloWorldTextView;    
  3. @Bind(R.id.app_name)    
  4. TextView mAppNameTextView;//view</span>  

4)綁定資源
[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@BindString(R.string.app_name)    
  2. String appName;//sting    
  3. @BindColor(R.color.red)    
  4. int textColor;//顏色    
  5. @BindDrawable(R.mipmap.ic_launcher)    
  6. Drawable drawable;//drawble    
  7. @Bind(R.id.imageview)    
  8. ImageView mImageView;    
  9. @Bind(R.id.checkbox)    
  10. CheckBox mCheckBox;    
  11. @BindDrawable(R.drawable.selector_image)    
  12. Drawable selector; </span>  

5)Adapter ViewHolder 綁定

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">public class TestAdapter extends BaseAdapter {    
  2.     private List<String> list;    
  3.     private Context context;    
  4.     
  5.     public TestAdapter(Context context, List<String> list) {    
  6.         this.list = list;    
  7.         this.context = context;    
  8.     }    
  9.     
  10.     @Override    
  11.     public int getCount() {    
  12.         return list==null ? 0 : list.size();    
  13.     }    
  14.     
  15.     @Override    
  16.     public Object getItem(int position) {    
  17.         return list.get(position);    
  18.     }    
  19.     
  20.     @Override    
  21.     public long getItemId(int position) {    
  22.         return position;    
  23.     }    
  24.     
  25.     @Override    
  26.     public View getView(int position, View convertView, ViewGroup parent) {    
  27.         ViewHolder holder;    
  28.         if (convertView == null) {    
  29.             convertView = LayoutInflater.from(context).inflate(R.layout.layout_list_item, null);    
  30.             holder = new ViewHolder(convertView);    
  31.             convertView.setTag(holder);    
  32.         } else {    
  33.             holder = (ViewHolder) convertView.getTag();    
  34.         }    
  35.         holder.textview.setText("item=====" + position);    
  36.         return convertView;    
  37.     }    
  38.     
  39.     static class ViewHolder {    
  40.         @Bind(R.id.hello_world)    
  41.         TextView textview;    
  42.     
  43.         public ViewHolder(View view) {    
  44.             ButterKnife.bind(this, view);    
  45.         }    
  46.     }    
  47. }  </span>  

 

6)點擊事件的綁定:不用聲明view,不用setOnClickLisener()就可以綁定點擊事件

a.直接綁定一個方法

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@OnClick(R.id.submit)    
  2. public void submit(View view) {    
  3.   // TODO submit data to server...    
  4. } </span>  

 

b.所有監聽方法的參數是可選的

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@OnClick(R.id.submit)    
  2. public void submit() {    
  3.   // TODO submit data to server...    
  4. }  </span>  

c.定義一個特定類型,它將自動被轉換

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@OnClick(R.id.submit)    
  2. public void sayHi(Button button) {    
  3.   button.setText("Hello!");    
  4. }</span>  

d.多個view統一處理同一個點擊事件,很方便,避免抽方法重複調用的麻煩

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@OnClick({ R.id.door1, R.id.door2, R.id.door3 })    
  2. public void pickDoor(DoorView door) {    
  3.   if (door.hasPrizeBehind()) {    
  4.     Toast.makeText(this"You win!", LENGTH_SHORT).show();    
  5.   } else {    
  6.     Toast.makeText(this"Try again", LENGTH_SHORT).show();    
  7.   }    
  8. } </span>  

 e.自定義view可以綁定自己的監聽,不指定id

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">public class FancyButton extends Button {    
  2.   @OnClick    
  3.   public void onClick() {    
  4.     // TODO do something!    
  5.   }    
  6. }  </span>  

f.給EditText加addTextChangedListener(即添加多回調方法的監聽的使用方法),利用指定回調,實現想回調的方法即可,哪個註解不會用點進去看下源碼上的註釋就會用了

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@OnTextChanged(value = R.id.mobileEditText, callback = OnTextChanged.Callback.BEFORE_TEXT_CHANGED)    
  2. void beforeTextChanged(CharSequence s, int start, int count, int after) {    
  3.     
  4. }    
  5. @OnTextChanged(value = R.id.mobileEditText, callback = OnTextChanged.Callback.TEXT_CHANGED)    
  6. void onTextChanged(CharSequence s, int start, int before, int count) {    
  7.     
  8. }    
  9. @OnTextChanged(value = R.id.mobileEditText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)    
  10. void afterTextChanged(Editable s) {    
  11.     
  12. }  </span>  


7)對一組View進行統一操作


a.裝入一個list

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">@Bind({ R.id.first_name, R.id.middle_name, R.id.last_name })    
  2. List<EditText> nameViews; </span>  

b.設置統一處理

[java] view plain copy
  1. <span style="font-family:SimSun;">static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {    
  2.   @Override public void apply(View view, int index) {    
  3.     view.setEnabled(false);    
  4.   }    
  5. };    
  6. static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {    
  7.   @Override public void set(View view, Boolean value, int index) {    
  8.     view.setEnabled(value);    
  9.   }    
  10. };<span style="color: silver; line-height: normal; background-color: rgb(248, 248, 248);"> </span><a target=_blank href="http://blog.csdn.net/itjianghuxiaoxiong/article/details/50177549#" class="ViewSource" title="view plain" style="line-height: normal; color: rgb(160, 160, 160); text-decoration: none; border: none; padding: 1px; margin: 0px 10px 0px 0px; display: inline-block; width: 16px; height: 16px; text-indent: -2000px; background-image: url("images/default/ico_plain.gif"); background-attachment: initial; background-color: inherit; background-size: initial; background-origin: initial; background-clip: initial; background-position: 0% 0%; background-repeat: no-repeat;">view plain</a></span><span data-mod="popu_168" style="font-size: 9px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; color: silver; line-height: normal;"> <a target=_blank href="http://blog.csdn.net/itjianghuxiaoxiong/article/details/50177549#" class="CopyToClipboard" title="copy" style="color: rgb(160, 160, 160); text-decoration: none; border: none; padding: 1px; margin: 0px 10px 0px 0px; font-size: 9px; display: inline-block; width: 16px; height: 16px; text-indent: -2000px; background-image: url("images/default/ico_copy.gif"); background-attachment: initial; background-color: inherit; background-size: initial; background-origin: initial; background-clip: initial; background-position: left top; background-repeat: no-repeat;">c</a></span>  


c.統一操作處理,例如設置是否可點,屬性等


[java] view plain copy
  1. <span style="font-family:SimSun;">ButterKnife.apply(nameViews, DISABLE);    
  2. ButterKnife.apply(nameViews, ENABLED, false);</span><span style="font-family:Arial;font-size: 14px;"> </span>  

8)可選綁定:默認情況下,“綁定”和“監聽”綁定都是必需的。如果不能找到目標視圖,則將拋出異常。所以做空處理


[java] view plain copy
  1. <span style="font-family:SimSun;">@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;    
  2.     
  3. @Nullable @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {    
  4.   // TODO ...    
  5. }  </span>  


三、代碼混淆

[java] view plain copy
  1. <span style="font-family:SimSun;font-size:14px;">-keep class butterknife.** { *; }    
  2. -dontwarn butterknife.internal.**    
  3. -keep class **$$ViewBinder { *; }    
  4.     
  5. -keepclasseswithmembernames class * {    
  6.     @butterknife.* <fields>;    
  7. }    
  8.     
  9. -keepclasseswithmembernames class * {    
  10.     @butterknife.* <methods>;    
  11. }  </span>  

四、Zelezny插件的使用

在AndroidStudio->File->Settings->Plugins->搜索Zelezny下載添加就行 ,可以快速生成對應組件的實例對象,不用手動寫。使用時,在要導入註解的Activity 或 Fragment 或 ViewHolder的layout資源代碼上,右鍵——>Generate——Generate ButterKnife Injections,然後就出現如圖的選擇框。(此動態圖來自官網)



發佈了30 篇原創文章 · 獲贊 13 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章