Android常用之Butterknife使用詳解
Butterknife簡介
Butterknife中文又名黃油刀,是 JakeWharton大神開源的一款Android檢視的欄位和方法繫結
快速註解框架.也是Android開發中比較常用的一款快速註解框架了,可以不用不斷的重複findViewById
,在各種場合下快速繫結view的多種事件,大大提高了開發的效率.
為什麼開發用Butterknife?
1、強大的View繫結和Click事件處理功能,簡化程式碼,提升開發效率2、方便的處理Adapter裡的ViewHolder繫結問題3、執行時不會影響APP效率,使用配置方便4、程式碼清晰,可讀性強5、............
使用配置
在 Android studio 專案中配置: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)必須在初始化繫結佈局檔案之後,否則會報錯
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,否則會造成記憶體洩漏.
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);//此處進行繫結
}
Butterknife具體使用
繫結View:
1.單個控制元件id 註解: @BindView()
@BindView(R.id.example)
Button example;
2.佈局內多個控制元件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陣列:@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陣列
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
繫結監聽事件
1.繫結控制元件點選事件:@OnClick( )
- 單個控制元件點選事件:
@OnClick(R.id.butter)
public void onClick(){
Toast.makeText(this, "繫結單個view事件", Toast.LENGTH_SHORT).show();
}
- 多個控制元件同一點選事件:
@OnClick({R.id.share_wechat,R.id.share_moments,R.id.share_weibo})
public void onClick(){
Toast.makeText(this, "都執行此事件", Toast.LENGTH_SHORT).show();
}
- 多個控制元件點選事件:
@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 設定一個長按事件
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;
}
//焦點改變
@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點選事件
@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進行管理初始化等操作,而Setter介面其實就是對view或者views的屬性或者值進行操作.使用 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("點選我");
}
}
};
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外掛使用
當熟悉了Butterknife 的基本用法後,有時候還是要寫很多@BindView()之類的,是不是很煩,沒關係,最後教你們一招偷懶的方式,當然是用外掛了,嘿嘿.
1.安裝外掛步驟如下:開啟Android studio:點選File--->Settings--->Plugins--->搜尋 Butterknife Zelezny--->下載安裝--->重啟Android studio.
做完以上步驟,就可以愉快的寫程式碼了.
2.使用外掛
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//將游標移到佈局檔案處
ButterKnife.bind(this);
}
右擊Generate,如下:
開啟就看見我們佈局檔案中所有控制元件了.選擇你需要的就可以開始了.
好了,關於Butterknife註解就結束到這裡了,還有很多用法沒有介紹到,不過並不妨礙我們愉快的使用Butterknife了,趕快去試試吧.
歡迎關注作者darryrzhong,更多幹貨等你來拿喲.
請賞個小紅心!因為你的鼓勵是我寫作的最大動力!
更多精彩文章請關注