现在安卓项目开发中,butterknife是比较常用的注解框架,从而简化了findViewById的重复使用,提高了编程的效率

然而为什么要使用butterknife?一方面是为了提高编程效率,一方面butterknife对系统性能是没有影响的,因为butterknife是在编译的时候生成新的class,不是运行时进行反射,所以对性能不会有影响

butterknife现在最新版本是butterknife8,不过开发中还是主要使用butterknife6和butterknife7

butterknife6和butterknife7用法还是稍稍有点不同的

 

(a)引入butterknife注解框架

在Android Studio中可以,很快直接引入,我们可以,选择项目->右键->open modules setting,然后选择Dependencies,选择绿色的Add按钮,输入com.jakewharton:butterknife:7.0.1或者com.jakewharton:butterknife:6.1.0等等,引入框架,也可以网上下载jar,然后选择add as library,添加到项目

Android系列之butterknife基本用法_github

 

(b)butterknife的主要用处

(i)Activity类里使用:

Demo:只要使用InjectView就可以,然后在onCreate方法里初始化

ButterKnife.inject(类名.this);
@InjectView(R.id.listview)
ListView listview;

@InjectView(R.id.tv_black)
TextView mBlack;

@InjectView(R.id.message_title)
TextView mTitle;

private HashMap<String,Object> map;

private Context mContext;

@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_group_post);
ButterKnife.inject(GroupPostActivity.this);
initView();
}

butterknife7就换成@Bind就可以,初始化换成ButterKnife.bind(this);


(ii)在Fragment类使用

 

public class SimpleFragment extends Fragment {

@InjectView(R.id.fragment_text_view)
TextView mTextView;

public SimpleFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_simple, container, false);
ButterKnife.inject(this, view);
mTextView.setText("TextView in Fragment are found!");
return view;
}
}


(iii)在事件处理里使用

onClickListener可以这样写了

 

@OnClick(R.id.basic_finish_a_button)
void finishA(View view) {
finish();
}


(iiii)在ListView和GridView里使用

 

@InjectViews({R.id.label_first_name, R.id.label_middle_name, R.id.label_last_name})
List<TextView> labelViews;

也可以在适配器里使用等等

 

下面提供参考文档

例子:​​https://github.com/mengdd/AndroidButterKnifeSample​

官网: ​​http://jakewharton.github.io/butterknife/​

Java Doc: ​​http://jakewharton.github.io/butterknife/javadoc/​

github上开源项目: ​​https://github.com/JakeWharton/butterknife​