Android Butterknife 使用

ButterKnife是AndroidStudio中一个应用非常广的插件,有着艺术般的体验,深受广大开发者的喜爱,只需要3步即可配置成功,想要抛弃findViewById请跟我来

1、首先先要下载ButterKnife

2、安装好插件之后,在project中的build.gradle中的dependencies中添加:

      classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8’ // 添加这行 

   

3、根据指定的位置插入代码 

     apply plugin: 'android-apt' //添加这行
    compile 'com.jakewharton:butterknife:8.5.1' //添加这行
    apt 'com.jakewharton:butterknife-compiler:8.5.1' //添加这行

配置完成之后,Sync Now一下,既可以开始使用,下图是使用教程: 

把光标放在布局代码上,按下Alt+Insert快捷键,选择“Generate Butterknife Injections”


绑定Activity
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    // 绑定
    ButterKnife.bind(this);
}
绑定Fragment
Unbinder unbinder;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View containerView = inflater.inflate(R.layout.frag_home,null);
    // 绑定
    unbinder = ButterKnife.bind(this,containerView);

    return containerView;
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    // 解绑
    unbinder.unbind();
}
绑定ViewHolder
public class RecyclerHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.item_label)
    TextView itemLabel;

    public RecyclerHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this,itemView);
    }
}
  • 绑定控件
@BindView(R.id.toolbar_title)
TextView toolbarTitle;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值