Android ButterKnife使用总结

来源:互联网 发布:烟台网亿网络好不好 编辑:程序博客网 时间:2024/05/16 09:38

让程序猿的偷懒来的更猛烈些吧~(づ。◕‿‿◕。)づ

ButterKnife其实就是一个依托Java的注解机制来实现辅助代码生成的框架

首先我们来完成以下环境配置:

你需要拥有butterknife的jar包。

然后项目的lib目录下,在build.gradle文件中声明。

然后就可以愉快地使用ButterKnife,来使我们的代码更加优雅。

不过在介绍使用方法之前,需要在Activity的onCreate中绑定一下,就像这样:

然后别忘了结束绑定:


常见的用法:

省去findViewById:

before:   TextViewtitleTv = (TextView)findViewById(R.id.actionbar_title);after:    @Bind(R.id.actionvar_title) public TextViewtitleTv ;

优化Adapter:

before:

private static class ViewHolder {       private TextView tv;}
after:
class ViewHolder {        @Bind(R.id.tv_content)        public TextView tv;        public ViewHolder(View view) {            ButterKnife.bind(this, view);        }    }

省略setOnClickListener:

before:

LinearLayout llytLeftArrow = (LinearLayout) findViewById(R.id.left_arrow_frame);llytLeftArrow.setOnClickListener(new View.OnClickListener(){public void onClick(View v){……}});
after:
@OnClick(R.id.left_arrow_frame)public void loadOneDayAfter(){……}

同理,可以省去onTouch,onItemLongClick,onItemClick……

同时,你可以一次指定多个id,为多个View绑定同一个事件。

@OnClick({R.id.id1,R.id.id2,R.id.id3})public void doSomething (){……}

对一View进行统一处理:

@Bind({ R.id.first_name, R.id.middle_name, R.id.last_name })  List<EditText> nameViews; static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() {  @Override public void apply(View view, int index) {      view.setEnabled(false);  //统一操作的具体内容  }  };  static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() {    @Override public void set(View view, Boolean value, int index) {      view.setEnabled(value);    }  };  ButterKnife.apply(nameViews, DISABLE);  ButterKnife.apply(nameViews, ENABLED, false);  

多方法的listener:

before:

titleTv.addTextChangedListener(new TextWatcher() {    @Override    public void beforeTextChanged(CharSequence s, int start, int count, int after) {    }    @Override    public void onTextChanged(CharSequence s, int start, int before, int count) {    }    @Override    public void afterTextChanged(Editable s) {    }});
after:

@OnTextChanged(value = R.id.titleTv, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)  void afterTextChanged(Editable s) {    } 
  

使用心得:

1.Activity ButterKnife.bind(this);必须在setContentView();之后

2.Fragment使用ButterKnife.bind(this,view);

3.属性布局不能用privateor static修饰,否则会报错o(︿+)o(参考:http://www.cnblogs.com/bugly/p/5680517.html)

4.setContentView()不能通过注解实现。

5.由于所有的注解都会在ButterKnife.bind(this)后开始,所以如果绑定牵扯逻辑顺序问题,不要使用ButterKnife

6.就减少代码行数来看,一些情况下可以不使用ButterKnife

findViewById(R.id.xxx).setVisbility(View.GONE);(只是用一次)

((TextView)findViewById(R.id.actionbar_title)).setText(R.string.str_btn_login);

减少不必要的全局变量


github:https://github.com/JakeWharton/butterknife


0 0
原创粉丝点击