ButterKnife使用詳解


版權(quán)聲明

原創(chuàng)作者:谷哥的小弟
博客地址:http://blog.csdn.net/lfdfhl

參考資料

準(zhǔn)備工作

  • 為Android Studio安裝插件Butterknife Zelezny
  • 在build.gradle的dependencies{}中加入

compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'

使用方式

  1. 綁定控件
class ExampleActivity extends Activity {
     @BindView(R.id.title) TextView title;
     @BindView(R.id.subtitle) TextView subtitle;
     @BindView(R.id.footer) TextView footer;
   
     @Override public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.simple_activity);
       ButterKnife.bind(this);
       // TODO Use fields...
     }
}
  1. 綁定資源
    @BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString.
class ExampleActivity extends Activity {
     @BindString(R.string.title) String title;
     @BindDrawable(R.drawable.graphic) Drawable graphic;
     @BindColor(R.color.red) int red; 
     @BindDimen(R.dimen.spacer) Float spacer; 
     // ...
}
  1. 綁定Fragment
public class FancyFragment extends Fragment {
     @BindView(R.id.button1) Button button1;
     @BindView(R.id.button2) Button button2;
     private Unbinder unbinder;
   
     @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b) {
       View view = inflater.inflate(R.layout.fragment, container, false);
       unbinder = ButterKnife.bind(this, view);
       // TODO Use fields...
       return view;
     }
   
     @Override public void onDestroyView() {
       super.onDestroyView();
       unbinder.unbind();
     }
}

在Fragment的onCreateView()中設(shè)置綁定,onDestroyView()中解綁

  1. 綁定Adapter
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);
       }
   
       holder.name.setText("John Doe");
       // etc...
   
       return view;
 }

 static class ViewHolder {
       @BindView(R.id.title) TextView name;
       @BindView(R.id.job_title) TextView jobTitle;
   
       public ViewHolder(View view) {
         ButterKnife.bind(this, view);
       }
     }
}
  1. 綁定Click事件監(jiān)聽
@OnClick(R.id.textView)
   public void clickView(){
       Toast.makeText(this,"click",Toast.LENGTH_SHORT).show();
   }

請注意方法應(yīng)該是public或者static的

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容