ButterKnife的使用

最近使用了一款特别好用的注解框架ButterKnife,在这里和大家分享一下
使用步骤如下:
1.在module的build.gradle顶部添加

apply plugin: 'com.jakewharton.butterknife'

在依赖中添加

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

2.在主项目的build.gradle修改配置

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        /**
        *添加如下代码
        **/
        classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'   
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

3.这样就可以在代码中使用了

public class MainActivity extends AppCompatActivity {

    @BindView( R.id.button )
    public Button button ;

    // 注意:button 的修饰类型不能是:private 或者 static 。 否则会报错:错误: @BindView fields must not be private or static. 

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_butterknife);
        //绑定activity
        ButterKnife.bind( this ) ;
        button.setText( "Hello World!");
    }
}

4.还有一些其他的功能:

·多控件注解

 @BindViews({R.id.tv_future1_date, R.id.tv_future2_date, R.id.tv_future3_date,
            R.id.tv_future4_date, R.id.tv_future5_date, R.id.tv_future6_date,})
    public List<TextView> dates;

· 多事件绑定

@OnClick({R.id.btn_login, R.id.btn_register})
    public void login(View view) {
        Log.e(TAG, "这里同时绑定了登陆和注册点击事件");
    }

· Adapter中绑定

public static class MyViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_msg)
        TextView textView;

        public LineViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

这里只列举几个,其他的功能可以查看
http://www.cnblogs.com/zhaoyanjun/p/6016341.html

荆轲刺秦王,大功已告成

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值