這段時間學習了下ButterKnife注解框架,學習的不是特別深入,但是基礎也差不多了,在此記錄總結一下。
ButterKnife是一個Android View注入的庫,主要是注解的使用,可以減少很多代碼的書寫,使代碼結構更加簡潔和整齊。ButterKnife可以避免findViewById的調用,android開發的人都知道在Android初始化控件對象的時候要不斷地調用findviewById,有多少控件就需要調用多少次,而使用ButterKnife可以省去findViewById的調用,不僅如此還可以省去監聽事件的冗長代碼,只需要一個注解就可以完成。下面我們來看看ButterKnife到底是如何使用的。
一、如何引入ButterKnife?
1. 首先是在Project的gradle中添加依賴:
1 dependencies { 2 //butterknife的導入 3 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 4 }
2. 在app的gradle中添加如下:
在gradle中添加:
1 apply plugin: 'android-apt'
在gradle的dependencies中添加:
dependencies { compile 'com.jakewharton:butterknife:8.4.0' apt 'com.jakewharton:butterknife-compiler:8.4.0' }
3. rebuild就完成了。
這里關於Project和app中build.gradle的區別可以參考這篇文章:Android Project和app中兩個build.gradle配置的區別
二、如何使用?
注意:button 的修飾類型不能是:private 或者 static 。 否則會報錯:錯誤: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)
(一)、View的綁定
1. 控件id的注解:@BindView()
1 @BindView(R.id.toolbar) 2 public Toolbar toolbar;
然后再Activity的onCreate()中調用:
1 ButterKnife.bind( this ) ;
2. 多個控件id 注解: @BindViews()
1 @BindViews({ R.id.button1 , R.id.button2 , R.id.button3 }) 2 public List<Button> buttonList ;
然后再Activity的onCreate()中調用:
1 ButterKnife.bind( this ) ;
3. 綁定其他View中的控件
Butter Knife提供了bind的幾個重載,只要傳入跟布局,便可以在任何對象中使用注解綁定。調用ButterKnife.bind(view. this);方法。但是一般調用 Unbinder unbinder=ButterKnife.bind(view, this)方法之后需要在調用 unbinder.unbind()解綁。
所以一般在activity中調用之后再綁定其他的view中的控件時我都會使用(四)中的方法。
(二)、資源的綁定
1 <resources> 2 <string name="hello">Hello</string> 3 <string-array name="array"> 4 <item>hello</item> 5 <item>hello</item> 6 <item>hello</item> 7 <item>hello</item> 8 </string-array> 9 </resources>
1. @BindString() :綁定string 字符串
1 @BindString(R.string.hello) 2 public String hello;
然后再Activity的onCreate中調用:
1 ButterKnife.bind( this ) ;
2. @BindArray() : 綁定string里面array數組
1 @BindArray(R.array.array) //綁定string里面array數組 2 String [] array;
然后再Activity的onCreate()中調用:
1 ButterKnife.bind( this ) ;
3. @BindBitmap( ) : 綁定Bitmap 資源
1 @BindBitmap(R.mipmap.ic_launcher) 2 public Bitmap bitmap;
然后再Activity的onCreate()中調用:
1 ButterKnife.bind( this ) ;
6. 其他資源
綁定BindColor(),BindDimen(),BindDrawable(),BindInt()等都是同樣的方法,(1). 綁定資源。 (2).調用ButterKnife.bind()方法。
(三)、事件的綁定
1. 綁定OnClick方法
1 @OnClick(R.id.login_activity_button_login) 2 public void clickLogin() { 3 }
然后再Activity的onCreate()中調用:
1 ButterKnife.bind( this ) ;
如果綁定多個id的話,用“,”逗號隔開。
(四)、其他
Butter Knife提供了一個findViewById的簡化代碼:findById,用這個方法可以在View、Activity和Dialog中找到想要View,而且,該方法使用的泛型來對返回值進行轉換,也就是說,你可以省去findViewById前面的強制轉換了。
1 View view = LayoutInflater.from(context).inflate(R.layout.thing, null); 2 TextView firstName = ButterKnife.findById(view, R.id.first_name);
ButterKnife.bind的調用可以被放在任何你想調用findViewById的地方。