(1)ButterKnife是什么?
在开发过程中,我们总是会写大量的findViewById和点击事件,像初始view、设置view监听这样简单而重复的操作让人觉得特别麻烦,当然不会偷懒的程序员不是好程序员,自然也出现了相应的解决方案--依赖注入。而ButterKnife则是依赖注入中相对简单易懂的很不错的开源框架,(其实ButterKnife也不算严格意义上的依赖注入,后面文章中会做分析)。但ButterKnife作为JakeWharton大神写的注解框架被广泛应用于android开发中,自然也有它的过人之处。下面对它的使用过程进行描述。
![](http://upload-images.jianshu.io/upload_images/1833901-93604043dc926440.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000)
butterKnife
(2)ButterKnife 有哪些优势?
ButterKnife的具体使用,请参考文章
http://blog.csdn.net/itjianghuxiaoxiong/article/details/50177549
它的具体优势:
1.强大的View绑定和Click事件处理功能,简化代码,提升开发效率
2.方便的处理Adapter里的ViewHolder绑定问题
3.运行时不会影响APP效率,使用配置方便
4.代码清晰,可读性强
![](http://upload-images.jianshu.io/upload_images/1833901-8222bb29fa4fc33d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/791)
butterknife的使用
(3) butterknife 和其他依赖注入框架的区别在哪里?
3.1 依赖注入框架的区别的联系:
其实主要在android中使用的依赖注入框架为Dagger、Butter Knife、RoboGuice、Android Annotations。这里提供链接:
Android's Options for Dependency Injection: Dagger, RoboGuice, and ButterKnife
对应的翻译文章:Android依赖注入:Dagger、RoboGuice和ButterKnife.
3.2 当然,这种典型的问题当然少不了StackOverflow上去看看,
![](http://upload-images.jianshu.io/upload_images/1833901-72185e77b35c915a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/885)
输入关键字
![](http://upload-images.jianshu.io/upload_images/1833901-9273185d27d7acf3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/820)
找到点赞最多的答案,肯定对你有帮助
大概意思:
Buffer knife目的为注入到view,所以能够在非activity里面注入,也能注入到inflate的views里面Dagger能够注入到任何你想要的对象,只要其在module类中。或者它是构造器。但是缺少对方法和字段的注入支持。Buffer knife只是避免样板代码,findViewById,仅此而已,所以不能算是一个真正的注入。只是一个view的代言。
(4)ButterKnife使用中有哪些注意的点呢?
注意:
Activity ButterKnife.bind(this);必须在setContentView();之后,且父类bind绑定后,子类不需要再bind
Fragment ButterKnife.bind(this, mRootView);
属性布局不能用private or static 修饰,否则会报错
setContentView()不能通过注解实现。
ButterKnife已经更新到版本7.0.1了,以前的版本中叫做@InjectView了,而现在改用叫@Bind,更加贴合语义。
在Fragment生命周期中,onDestoryView也需要Butterknife.unbind(this)
ButterKnife不能再你的library module中使用哦!!这是因为你的library中的R字段的id值不是final类型的,但是你自己的应用module中确是final类型的。针对这个问题,有人在Jack的github上issue过这个问题,他本人也做了回答,点击这里。
![](http://upload-images.jianshu.io/upload_images/1833901-372de11943fa3b41.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/275)
属性必须是一个常量
(5)我还想更懒怎么办?
哈哈,这里说的是添加插件,让你写代码更快捷。
Zelezny插件的使用的使用能让你变得更懒(也代码更快)
![](http://upload-images.jianshu.io/upload_images/1833901-f6092a8aeda8a37e.gif?imageMogr2/auto-orient/strip%7CimageView2/2/w/712)
**Zelezny插件的使用**
5.1怎么使用插件?
![](http://upload-images.jianshu.io/upload_images/1833901-2bc52b5e7e37e664.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/927)
插件使用步骤1
![](http://upload-images.jianshu.io/upload_images/1833901-be9332ca2729f742.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/738)
插件使用步骤2
![](http://upload-images.jianshu.io/upload_images/1833901-551d75762a9c1ef4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/781)
插件使用步骤3
(6)推荐链接:
3Android's Options for Dependency Injection: Dagger, RoboGuice, and ButterKnife(这里是翻译文章链接Android依赖注入:Dagger、RoboGuice和ButterKnife)