懒人库ButterKnife的应用

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/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值