
前言
Butterknife——相信多同學都知道,這是一個注解框架,一般在綁定View的時候使用。不得不說,這個框架"有毒",用了就上癮,連寫個Demo都要去導這個庫。
想必大多數(shù)同學都用過ButterKnife,可能你會說“不就是代替了findViewById()嗎?”。我想說,確實不只是有findViewById()這個功能。不得不承認,在這之前,我對ButterKnife的使用,也只停留在綁定視圖和點擊事件上。??????
介紹
ButterKnife我已經(jīng)用了好一段時間了,它除了方便,還是方便。ButterKnife為我們簡化了很多代碼,具體有的作用,可以下面的例子來了解。
看看官方的介紹:
Field and method binding for Android views which uses annotation processing to generate boilerplate code for you
使用注解生成模塊代碼,用于把一些字段和方法綁定到 Android 的 View。
優(yōu)勢
- 強大的
View綁定和Click事件等處理功能,簡化代碼,提升開發(fā)效率 - 運行時不會影響APP效率,使用配置方便
- 代碼清晰,可讀性強
申明
可能有些人對ButterKnife有一些誤解,認為ButterKnife是通過反射來實現(xiàn)的。其實不然,相比緩慢的反射機制,ButterKnife用的APT(Annotation Processing Tool)編譯時解析技術。動態(tài)生成綁定事件或者控件的java代碼,然后在運行的時候,直接調用bind方法完成綁定,因此你不必擔心注解的性能問題。騷年,放心去用吧。
如果你對原理感興趣,可以點擊這里
使用
啰嗦了半天,終于說到正題了~~
依賴
Project的build.gradle文件中:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
}
}
Module的build.gradle文件中:
apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'
dependencies {
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}
單個View——@BindView
-
在Activity中使用
例:綁定布局中的TextView、Button、EditText。 - 沒有ButterKnife時,各種煩人的
findViewById()和強轉:
TextView textView = (TextView) findViewById(R.id.text_view);
Button button = (Button) findViewById(R.id.button);
EditText editText = (EditText) findViewById(R.id.edit_text);
- 使用ButterKnife后:
先綁定對應的View
@BindView(R.id.text_view)
TextView mTextView;
@BindView(R.id.button)
Button mButton;
@BindView(R.id.edit_text)
EditText mEditText;
然后在onCreate()的setContentView()下添加ButterKnife.bind(this);:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
然后這些View就可以隨心所欲的使用了,方便吧!
注意:這里的
View不可以是private或static類型
-
在Fragment、Adapter中使用
除了Activity,我們常用的場景還有Fragment,以及Adapter。用法跟在Activity中大致相似。 - Fragment中
例:綁定布局中的TextView、Button、EditText。
public class MainFragment extends Fragment {
@BindView(R.id.text_view)
TextView mTextView;
@BindView(R.id.button)
Button mButton;
@BindView(R.id.edit_text)
EditText mEditText;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_main, container, false);
ButterKnife.bind(this, rootView);//這里有些不同
return rootView;
}
}
提示:如果我們需要在某個時候將
Fragment中的view設置為null,這時候需要用到Unbinder。在onCreateView中使用bind方法時,會返回一個Unbinder對象,該對象中有的unbinder方法,可以將Fragment中的View設置為null
- Adapter中
例:綁定布局中的TextView、Button。
public class MyAdapter extends BaseAdapter {
@Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder holder;
if (view != null) {
holder = (ViewHolder) view.getTag();
} else {
view = inflater.inflate(R.layout.whatever, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
}
//....
return view;
}
static class ViewHolder {
@BindView(R.id.text_view) TextView mTextView;
@BindView(R.id.button) Button mButton;;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
提示:在使用
BindView方法的時候,如果目標View沒有找的的話,會拋出異常。如果不想受到這個異常,可以使用@Nullable
@Nullable @BindView(R.id.text_view)
多個View——@BindViews
使用這種綁定時,你可以使用apply()方法。該函數(shù)相當于將在這個列表中每一個元素上進行調用.利用ButterKnife的Action或Setter接口來執(zhí)行一些簡單的操作
- 例:隱藏指定的
View。
先使用List<View>綁定視圖
@BindViews({R.id.text_view, R.id.button, R.id.edit_text})
List<View> mViews;
- 使用
Action
final ButterKnife.Action<View> VIEWS_GONE = new ButterKnife.Action<View>() {
@Override
public void apply(@NonNull View view, int index) {
view.setVisibility(View.GONE);
}
};
ButterKnife.apply(mViews, VIEWS_GONE);
- 使用Setter
final ButterKnife.Setter<View, Boolean> VIEWS_VISIAVLE = new ButterKnife.Setter<View, Boolean>() {
@Override
public void set(@NonNull View view, Boolean value, int index) {
final int IS_VISIAVLE = value ? View.VISIBLE : View.GONE;
view.setVisibility(IS_VISIAVLE);
}
};
ButterKnife.apply(mViews, VIEWS_VISIAVLE, false);
- Android屬性也可以和
apply方法一起使用。
ButterKnife.apply(nameViews, View.ALPHA, 0.0f);
點擊事件——@OnClick
在使用的過程中,除了@BindView,還有@OnClick也是經(jīng)常用到的。
- 例:為
Button設置點擊事件
@OnClick(R.id.button)
public void onButtonClick(View view) {
Toast.makeText(this, "button被點擊了", Toast.LENGTH_SHORT).show();
}
參數(shù)View就是被點擊的視圖
如果可以確認View的具體類型,可以這樣寫。如:已知為Button類型
@OnClick(R.id.button)
public void onButtonClick(Button button) {
Toast.makeText(this, "button被點擊了", Toast.LENGTH_SHORT).show();
}
如果不需要用到參數(shù)View,也可以去掉
@OnClick(R.id.button)
public void onButtonClick() {
Toast.makeText(this, "button被點擊了", Toast.LENGTH_SHORT).show();
}
- 例:多個點擊事件
@OnClick({R.id.text_view, R.id.button, R.id.edit_text})
public void onTextviewClick(View view) {
switch (view.getId()){
case R.id.text_view:
Toast.makeText(this, "text_view被點擊了", Toast.LENGTH_SHORT).show();
break;
case R.id.button:
Toast.makeText(this, "button被點擊了", Toast.LENGTH_SHORT).show();
break;
case R.id.edit_text:
Toast.makeText(this, "edit_text被點擊了", Toast.LENGTH_SHORT).show();
break;
}
}
- 例:
item的點擊事件
@BindView(R.id.list_view)
ListView mListView;
private String[] strs = {"1","2","3","4","5"};
mListView.setAdapter(new ArrayAdapter<String>(getContext(),
android.R.layout.simple_list_item_1, strs));
@OnItemClick(R.id.list_view)
void onItemClick(int potion) {
Toast.makeText(getContext(), "點擊了:" + potion, Toast.LENGTH_SHORT).show();
}
有@OnItemClick,當然也有@OnItemLongClick。具體的用法我就不寫了...
- 自定義
View綁定事件監(jiān)聽時無需ID
public class FancyButton extends Button {
@OnClick
public void onClick() {
// TODO do something!
}
}
注意:
1、方法名可以隨便取
2、跟View一樣,方法也不能為private或static類型
資源綁定
可以利用@BindBool,@BindColor,@BindDimen,@BindDrawable,@BindInt,@BindString來綁定資源,如下
class MainActivity extends Activity {
@BindString(R.string.title) String title;
@BindDrawable(R.drawable.graphic) Drawable graphic;
@BindColor(R.color.red) int red; // int or ColorStateList field
@BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field
// ...
}
findById方法
如果在某些場景下,你真的需要用到findViewById()方法。不用擔心,ButterKnife中包含了findById()方法來替代findViewById(),可以在View,Activity, 或Dialog中使用
View view = LayoutInflater.from(context).inflate(R.layout.thing, null);
TextView firstName = ButterKnife.findById(view, R.id.first_name);
TextView lastName = ButterKnife.findById(view, R.id.last_name);
ImageView photo = ButterKnife.findById(view, R.id.photo);
Zelezny插件
如果你是像我一樣高(lan)效(duo)的程序員,一點都不想寫這些東西。那么福利來了,那就是Zelezny插件(Android Studio)。只要在布局中寫上'id',所有綁定的代碼自動生成。厲害了
-
安裝插件
安裝插件 -
使用
然后只要右鍵布局id上,選擇Generate,點擊Generate Butterknife Injections,該插件會從對應的布局中查找有id屬性的View,然后會出現(xiàn)在對應的選擇頁面。點擊Confirm即可。
操作
最后的提示
幾點有關ButterKnife的提示,使用時避免踩坑。
- Activity:
ButterKnife.bind(this);
必須在setContentView();之后,且父類bind綁定后,子類不需要再bind - Fragment :
ButterKnife.bind(this, mRootView); - 屬性布局不能用
private或static修飾,否則會報錯 -
setContentView()不能通過注解實現(xiàn)。 - ButterKnife已經(jīng)更新到版本8.x了,以前的版本中叫做
@InjectView,7.x中叫@Bind,而現(xiàn)在改用叫@BindView。
參考資料
官方Doc
GitHub
ButterKnife源碼分析
Android Butter Knife 框架——最好用的View注入
絕對不容錯過,ButterKnife 使用詳談
以上有錯誤之處,感謝指出

