Android ButterKnife注解框架使用
这段时间学习了下ButterKnife注解框架,学习的不是特别深入,但是基础也差不多了,在此记录总结一下。
ButterKnife是一个Android View注入的库,主要是注解的使用,可以减少很多代码的书写,使代码结构更加简洁和整齐。ButterKnife可以避免findViewById的调用,Android开发的人都知道在Android初始化控件对象的时候要不断地调用findviewById,有多少控件就需要调用多少次,而使用ButterKnife可以省去findViewById的调用,不仅如此还可以省去监听事件的冗长代码,只需要一个注解就可以完成。下面我们来看看ButterKnife到底是如何使用的。
一、如何引入ButterKnife?
1. 首先是在Project的gradle中添加依赖:
dependencies { //butterknife的导入 classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'}
2. 在app的gradle中添加如下:
在gradle中添加:
apply plugin: 'android-apt'
在gradle的dependencies中添加:
dependencies { compile 'com.jakewharton:butterknife:8.4.0' apt 'com.jakewharton:butterknife-compiler:8.4.0'}
3. rebuild就完成了。
这里关于Project和app中build.gradle的区别可以参考这篇文章:Android Project和app中两个build.gradle配置的区别
二、如何使用?
注意:button 的修饰类型不能是:private 或者 static 。 否则会报错:错误: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)
(一)、View的绑定
1. 控件id的注解:@BindView()
@BindView(R.id.toolbar)public Toolbar toolbar;
然后再Activity的onCreate()中调用:
ButterKnife.bind( this ) ;
2. 多个控件id 注解: @BindViews()
@BindViews({ R.id.button1 , R.id.button2 , R.id.button3 }) public List
然后再Activity的onCreate()中调用:
ButterKnife.bind( this ) ;
3. 绑定其他View中的控件
Butter Knife提供了bind的几个重载,只要传入跟布局,便可以在任何对象中使用注解绑定。调用ButterKnife.bind(view. this);方法。但是一般调用 Unbinder unbinder=ButterKnife.bind(view, this)方法之后需要在调用 unbinder.unbind()解绑。
所以一般在activity中调用之后再绑定其他的view中的控件时我都会使用(四)中的方法。
(二)、资源的绑定
<resources> <string name="hello">Hellostring> <string-array name="array"> <item>helloitem> <item>helloitem> <item>helloitem> <item>helloitem> string-array>resources>
1. @BindString() :绑定string 字符串
@BindString(R.string.hello) public String hello;
然后再Activity的onCreate中调用:
ButterKnife.bind( this ) ;
2. @BindArray() : 绑定string里面array数组
@BindArray(R.array.array) //绑定string里面array数组 String [] array;
然后再Activity的onCreate()中调用:
ButterKnife.bind( this ) ;
3. @BindBitmap( ) : 绑定Bitmap 资源
@BindBitmap(R.mipmap.ic_launcher) public Bitmap bitmap;
然后再Activity的onCreate()中调用:
ButterKnife.bind( this ) ;
6. 其他资源
绑定BindColor(),BindDimen(),BindDrawable(),BindInt()等都是同样的方法,(1). 绑定资源。 (2).调用ButterKnife.bind()方法。
(三)、事件的绑定
1. 绑定OnClick方法
@OnClick(R.id.login_activity_button_login) public void clickLogin() { }
然后再Activity的onCreate()中调用:
ButterKnife.bind( this ) ;
如果绑定多个id的话,用“,”逗号隔开。
(四)、其他
Butter Knife提供了一个findViewById的简化代码:findById,用这个方法可以在View、Activity和Dialog中找到想要View,而且,该方法使用的泛型来对返回值进行转换,也就是说,你可以省去findViewById前面的强制转换了。
View view = LayoutInflater.from(context).inflate(R.layout.thing, null);TextView firstName = ButterKnife.findById(view, R.id.first_name);
ButterKnife.bind的调用可以被放在任何你想调用findViewById的地方。
更多相关文章
- Android中的数据绑定框架DataBinding(对比AngularJS双向数据绑定
- Android Chronometer控件开发
- Android 控件一 TextView
- Android 控件二 Button
- Android控件TextView中ellipsize属性(设置当文字长度超过textview
- android控件背景揭密--NinePatch
- Android spinner控件的实现
- android动态创建控件
- Android应用开发——TextView控件属性列表