1、关于ButterKnife的配置
在Module的gradle中[截止目前版本8.4.0]
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0' compile 'com.android.support:appcompat-v7:24.2.1'
2、关于ButterKnife的注册
调用ButterKnife.bind可以使你在任何地方使用
在activity上使用 ButterKnife.bind(this);
在非activity上使用ButterKnife.bind(this,view);
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view=inflater.inflate(R.layout.activity_main,null,false); ButterKnife.bind(this,view); return view; }
3、绑定View控件
/**单个View控件的绑定*/
@BindView(R.id.btn_login)
/**多个控件的绑定可以写在List或者Array中*/
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;
4、资源绑定
@BindString(R.string.title) String title;
@BindDrawable(R.drawable.graphic) Drawable graphic;
@BindColor(R.color.red) int red; // int or ColorStateList field
@BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field
5、监听器绑定
监听器可以直接注解到方法上
@OnClick(R.id.submit)
public void submit(View view) {
// TODO submit data to server...
}
监听器方法的参数是可选的(监听器是可以带参数的)
@OnClick(R.id.submit)
public void sayHi(Button button) {
button.setText("Hello!");
}
多个控件可以绑定同一个监听器
@OnClick({R.id.button,R.id.button2,R.id.button4,R.id.button3}) public void onClick(View view){ switch (view.getId()){ case R.id.button: Log.v(LOG,"点击button"); break; case R.id.button2: Log.d(LOG,"点击button2"); break; case R.id.button3: Log.i(LOG,"点击button3"); break; case R.id.button4: Log.w(LOG,"点击button4"); break; }
6、Fragment重置building
Fragment的生命周期不同于Activity,当Butterknife在onCreateView上进行绑定时,需要在onDestroyView上进行解绑,Butterknife.bind()方法提供了一个Unbinder 返回值,在onDestroyView上调用相关的unbinder方法即可
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 savedInstanceState) {
View view = inflater.inflate(R.layout.fancy_fragment, container,false);
unbinder = ButterKnife.bind(this, view);
// TODO Use fields...
return view;
}
@Override public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}}
本文大部分例子来自官网,伙伴们可以直接查看
http://jakewharton.github.io/butterknife/