Butterknife中文又名黃油刀,是 JakeWharton大神開源的一款Android視圖的字段和方法綁定
快速註解框架.也是Android開發中比較經常使用的一款快速註解框架了,能夠不用不斷的重複findViewById
,在各類場合下快速綁定view的多種事件,大大提升了開發的效率.android
爲何開發用Butterknife?
一、強大的View綁定和Click事件處理功能,簡化代碼,提高開發效率
二、方便的處理Adapter裏的ViewHolder綁定問題
三、運行時不會影響APP效率,使用配置方便
四、代碼清晰,可讀性強
五、............git
使用配置
build.gradle
中添加以下配置:dependencies { implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' }
簡單使用以下:github
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... } }
1.在 Android project的build.gradle
中添加以下配置:segmentfault
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.
以下:app
class ExampleActivity extends Activity { @BindView(R2.id.user) EditText username; @BindView(R2.id.pass) EditText password; ... }
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:maven
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:ide
@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);//此處進行綁定 }
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接口主要是爲了對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 的基本用法後,有時候仍是要寫不少@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,更多幹貨等你來拿喲.
更多精彩文章請關注