Butterknife的使用

butterknife的使用

简介:ButterKnife是一个View注入框架,可以减少findViewById以及setOnClickListener代码。

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

一、添加依赖

1.1 主项目添加

在module的build.gredle 文件中的dependencies标签中添加

dependencies {
    compile 'com.jakewharton:butterknife:8.5.1'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
}

1.2 Library Module添加

如果Library Module也需要用到,则通过以下方式添加。

1.2.1 在Library Module的build.gredle 文件中的dependencies标签下添加

classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'

1.2.2 在Library Module的build.gredle 文件中添加

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'

二、如何使用

2.1 在Activity中使用

2.2 在Fragment中使用

2.3 view的绑定

2.3.1 单个View绑定 @BindView()

2.3.2 多个View绑定 @BindViews()

绑定Views

@BindViews({ R.id.button1, R.id.button2,  R.id.button3 })
public List<Button> buttonList ;

操作Views

buttonList.get( 0 ).setText( "hello 1 ");
buttonList.get( 1 ).setText( "hello 2 ");
buttonList.get( 2 ).setText( "hello 3 ");

2.3.3 绑定String @BindString()

2.3.4 绑定string里面array数组 @BindArray()

2.3.5 绑定Bitmap @BindBitmap()

2.3.6 绑定一个Color @BindColor()

可以绑定的类型:

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

2.3.7 绑定点击事件 @OnClick()

2.3.8 绑定长按事件 @OnLongClick()

可以绑定的类型:

三、在Android Studio上安装ButterKnife插件

3.1 打开Android Studio的Settins–>Pliugins,搜索Zelezny

3.2 安装插件

3.3 重启Android Studio

3.4 使用快捷方式

3.4.1 将光标放置到setContentView(R.layout.activity_login),右击选择Generate

3.4.2 选择Generate Butterknife injections

3.4.3 选择要绑定的控件,点击Comfirm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值