ButterKnife的介绍
ButterKnife是一个支持View注入的框架。通常要写很多findViewById来初始化View对象,有了ButterKnife可以很轻松的省去这些步骤。ButterKnife是大神JakeWharton的力作,目前使用很广。最重要的一点,使用ButterKnife对性能基本没有损失,因为ButterKnife用到的注解并不是在运行时反射的,而是在编译的时候生成新的class。本文中ButterKnife的版本是v7.0.1。官方网址:http://jakewharton.github.io/butterknife/
使用时应注意
Activity ButterKnife.bind(this)
;必须在setContentView()
;之后,且父类bind绑定后,子类不需要再bindFragment ButterKnife.bind(this, mRootView)
;- 属性布局不能用
private or static
修饰,否则会报错 setContentView()
不能通过注解实现。(其他的有些注解框架可以)
使用方法:
- 如果使用Eclipse,可以去官网下载jar包导入
- 如果使用AndroidStudio可以直接在gradle中添加依赖
compile 'com.jakewharton:butterknife:7.0.1'
在Activity中绑定
public class MainActivity extends AppCompatActivity{
//给指定的TextView绑定id
@Bind(R.id.tv)
TextView tv;
//给指定的Button绑定id
@Bind(R.id.btn)
Button btn;
@Ov