Butterknife簡介
Butterknife中文又名黃油刀,是 JakeWharton大神開源的一款Android視圖的字段和方法綁定
快速注解框架.也是Android開發(fā)中比較常用的一款快速注解框架了,可以不用不斷的重復(fù)findViewById
,在各種場合下快速綁定view的多種事件,大大提高了開發(fā)的效率.
為什么開發(fā)用Butterknife?
1翁巍、強(qiáng)大的View綁定和Click事件處理功能,簡化代碼休雌,提升開發(fā)效率
2灶壶、方便的處理Adapter里的ViewHolder綁定問題
3、運(yùn)行時不會影響APP效率杈曲,使用配置方便
4驰凛、代碼清晰,可讀性強(qiáng)
5担扑、............
使用配置
在 Android studio 項(xiàng)目中配置:Butterknife:
一.在主Moduel中的build.gradle
中添加如下配置:
dependencies {
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
簡單使用如下:
class ExampleActivity extends Activity {
@BindView(R.id.user) EditText username;
@BindView(R.id.pass) EditText password;
@BindString(R.string.login_error) String loginErrorMessage;
@OnClick(R.id.submit) void submit() {
// TODO call server...
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_activity);
ButterKnife.bind(this);
// TODO Use fields...
}
}
二.在Library projects中使用(按個人需求而定)
1.在 Android project的build.gradle
中添加如下配置:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
}
}
2.在Library的build.gradle
中添加如下配置:
apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'
值得注意的是,在Library中使用Butterknife注解使用的是R2.而不是R.
如下:
class ExampleActivity extends Activity {
@BindView(R2.id.user) EditText username;
@BindView(R2.id.pass) EditText password;
...
}
ButterKnife的基本使用詳解
ButterKnife使用場景如下:
1.在Activity中綁定ButterKnife:
public class MainActivity extends AppCompatActivity {
@BindView(R.id.butter)
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.butter)
public void onClick(){
Log.e("111111","11111");
Toast.makeText(this, "綁定單個view事件", Toast.LENGTH_SHORT).show();
}
}
值得注意的是:ButterKnife.bind(this)必須在初始化綁定布局文件之后,否則會報(bào)錯
2.在Fragment中綁定ButterKnife:
public class ExampleFragment extends Fragment {
private Unbinder unbinder;
@BindView(R.id.example)
Button example;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = View.inflate(getContext(),R.layout.fragment_example,null);
unbinder = ButterKnife.bind(this,view);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();//視圖銷毀時必須解綁
}
}
值得注意的是:在Fragment中需要在視圖銷毀時解綁Butterknife,否則會造成內(nèi)存泄漏.
3.在Adapter的ViewHolder中綁定Butterknife:
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recy_dynamic_state_item,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(itemView);//此處將view傳入
itemView.setOnClickListener(this);
return myViewHolder;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.iv_photo)
SimpleDraweeView simpleDraweeView;
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.tv_detail)
TextView tvDetail;
@BindView(R.id.date)
TextView date;
@BindView(R.id.avatar_user)
SimpleDraweeView avatarUser;
@BindView(R.id.username)
TextView userName;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this,itemView);//此處進(jìn)行綁定
}
Butterknife具體使用
綁定View:
1.單個控件id 注解: @BindView()
@BindView(R.id.example)
Button example;
2.布局內(nèi)多個控件id 注解: @BindViews()
@BindViews({R.id.butter,R.id.butter1,R.id.butter2})
List<Button> buttons;
綁定資源文件
1.綁定string 字符串:@BindString()
@BindString(R.string.app_name) //綁定資源文件中string字符串
String name;
2.綁定array數(shù)組:@BindArray()
<resources>
<string name="app_name">開眼視頻</string>
<string-array name="weather">
<item>高溫</item>
<item>低溫</item>
<item>陰天</item>
<item>雨天</item>
<item>晴天</item>
</string-array>
</resources>
@BindArray(R.array.weather) //綁定string資源里面array數(shù)組
String [] weathers ;
3.綁定顏色值:@BindColor( )
@BindColor( R.color.colorPrimary) //綁定color文件中顏色值
int colorPrimary;
4.綁定Bitmap:@BindBitmap( )
@BindBitmap(R.mipmap.ic_launcher)
Bitmap bitmap;
5.其他資源綁定:
@BindBool(R.bool.is_tablet) boolean isTablet; //綁定真假boolean
@BindFont(R.font.comic_sans) Typeface comicSans; //綁定字體文字
@BindDimen(R.dimen.horizontal_gap) int gapPx //綁定尺寸
@BindDimen(R.dimen.horizontal_gap) float gap; //綁定尺寸
@BindAnim(R.anim.fade_in) Animation fadeIn; //綁定動畫
@BindDrawable(R.drawable.placeholder) Drawable placeholder;//綁定Drawable
綁定監(jiān)聽事件
1.綁定控件點(diǎn)擊事件:@OnClick( )
- 單個控件點(diǎn)擊事件:
@OnClick(R.id.butter)
public void onClick(){
Toast.makeText(this, "綁定單個view事件", Toast.LENGTH_SHORT).show();
}
- 多個控件同一點(diǎn)擊事件:
@OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
public void onClick(){
Toast.makeText(this, "都執(zhí)行此事件", Toast.LENGTH_SHORT).show();
}
- 多個控件點(diǎn)擊事件:
@OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
public void onClick(View v) {
switch (v.getId()){
case R.id.share_wechat:
sharePlatform(Wechat.NAME);
break;
case R.id.share_moments:
sharePlatform(WechatMoments.NAME);
break;
case R.id.share_weibo:
sharePlatform(SinaWeibo.NAME);
break;
}
}
2.綁定控件長按事件:@OnLongClick( )
@OnLongClick( R.id.button1 ) //給 button1 設(shè)置一個長按事件
public boolean onLongClick (){
Toast.makeText(this, "is a long click", Toast.LENGTH_SHORT).show();
return true ;
}
3.其他事件綁定
//選中恰响,選中取消
@OnCheckedChanged(R.id.example)
public void onChecked(boolean checked) {
Toast.makeText(this, checked ? "Checked!" : "Unchecked!", Toast.LENGTH_SHORT).show();
}
//軟鍵盤的功能按鍵
@OnEditorAction(R.id.example)
public boolean onEditorAction(KeyEvent key) {
Toast.makeText(this, "Pressed: " + key, Toast.LENGTH_SHORT).show();
return true;
}
//焦點(diǎn)改變
@OnFocusChange(R.id.example)
public void onFocusChanged(boolean focused) {
Toast.makeText(this, focused ? "Gained focus" : "Lost focus", Toast.LENGTH_SHORT).show();
}
//Item長按,返回true則可以攔截onItemClick
@OnItemLongClick(R.id.example_list)
public boolean onItemLongClick(int position) {
Toast.makeText(this, "Long clicked position " + position + "!", Toast.LENGTH_SHORT).show();
return true;
}
//Item點(diǎn)擊事件
@OnItemClick(R.id.example_list)
public void onItemClick(int position) {
Toast.makeText(this, "Clicked position " + position + "!", Toast.LENGTH_SHORT).show();
}
//Item被選擇事件
@OnItemSelected(R.id.example_list)
public void onItemSelected(int position) {
Toast.makeText(this, "Selected position " + position + "!", Toast.LENGTH_SHORT).show();
}
//EditText里面的文本變化事件
@OnTextChanged(R.id.example)
public void onTextChanged(CharSequence text) {
Toast.makeText(this, "Text changed: " + text, Toast.LENGTH_SHORT).show();
}
//頁面改變事件
@OnPageChange(R.id.example_pager)
public void onPageSelected(int position) {
Toast.makeText(this, "Selected " + position + "!", Toast.LENGTH_SHORT).show();
}
//觸摸事件
@OnTouch(R.id.example)
public boolean onTouch() {
Toast.makeText(this, "Touched!", Toast.LENGTH_SHORT).show();
return false;
}
Action接口與Setter接口
Action接口主要是為了對View或者Views進(jìn)行管理初始化等操作涌献,而Setter接口其實(shí)就是對view或者views的屬性或者值進(jìn)行操作.使用 ButterKnife.apply()方法啟用接口.
ButterKnife.Action<View> action = new ButterKnife.Action<View>() {
@Override
public void apply(@NonNull View view, int index) {
if (view instanceof Button ){
Button button = (Button) view;
button.setText("點(diǎn)擊我");
}
}
};
ButterKnife.Setter<View,Boolean> setter = new ButterKnife.Setter<View, Boolean>() {
@Override
public void set(@NonNull View view, Boolean value, int index) {
view.setEnabled(value);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
ButterKnife.apply(buttons,action);//初始化或修改每個view的屬性值
ButterKnife.apply(buttons,setter,true);
}
Butterknife Zelezny插件使用
當(dāng)熟悉了Butterknife 的基本用法后,有時候還是要寫很多@BindView()之類的,是不是很煩,沒關(guān)系,最后教你們一招偷懶的方式,當(dāng)然是用插件了,嘿嘿.
1.安裝插件
步驟如下:
打開Android studio:點(diǎn)擊File--->Settings--->Plugins--->搜索 Butterknife Zelezny--->下載安裝--->重啟Android studio.
做完以上步驟,就可以愉快的寫代碼了.
2.使用插件
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//將光標(biāo)移到布局文件處
ButterKnife.bind(this);
}
右擊Generate,如下:
打開就看見我們布局文件中所有控件了.選擇你需要的就可以開始了.
好了,關(guān)于Butterknife注解就結(jié)束到這里了,還有很多用法沒有介紹到,不過并不妨礙我們愉快的使用Butterknife了,趕快去試試吧.
歡迎關(guān)注作者darryrzhong,更多干貨等你來拿喲.
請賞個小紅心胚宦!因?yàn)槟愕墓膭钍俏覍懽鞯淖畲髣恿Γ?/h3>
更多精彩文章請關(guān)注
更多精彩文章請關(guān)注