引言
自制一个简易的计算器,怎奈按钮过多,需要添加大量的监听。怎么办?ButterKnife前来报道。
ButterKnife的Github地址:https://github.com/JakeWharton/butterknife
ButterKnife的注入
添加依赖
Configure your project-level build.gradle to include the ‘android-apt’ plugin:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
Then, apply the ‘android-apt’ plugin in your module-level build.gradle and add the Butter Knife dependencies:
apply plugin: 'android-apt'
android {
...
}
dependencies {
compile 'com.jakewharton:butterknife:8.4.0'
apt 'com.jakewharton:butterknife-compiler:8.4.0'
}
Activity注入
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
Fragment注入
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.keybord_normal_fragment, container, false);
ButterKnife.bind(this, view);
return view;
}
ViewHolder注入
static class ViewHolder {
@Bind(R.id.name) TextView name;
@Bind(R.id.password) TextView pwd;
public ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
其余绑定
//资源绑定:
@BindColor(R.color.red) int red;
//控件绑定:
@BindView(R.id.home_show_content_tv)
TextView mTvShowContent;
onClick事件绑定:
@OnClick({R.id.cal_num_1_btn, R.id.cal_num_2_btn})
public void click(View view){
...
}
相关参考资料:
http://blog.csdn.net/i374711088/article/details/49102003