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