最近使用了一款特别好用的注解框架ButterKnife,在这里和大家分享一下
使用步骤如下:
1.在module的build.gradle顶部添加
apply plugin: 'com.jakewharton.butterknife'
在依赖中添加
compile 'com.jakewharton:butterknife:8.5.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.5.1'
2.在主项目的build.gradle修改配置
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
/**
*添加如下代码
**/
classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
3.这样就可以在代码中使用了
public class MainActivity extends AppCompatActivity {
@BindView( R.id.button )
public Button button ;
// 注意:button 的修饰类型不能是:private 或者 static 。 否则会报错:错误: @BindView fields must not be private or static.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_butterknife);
//绑定activity
ButterKnife.bind( this ) ;
button.setText( "Hello World!");
}
}
4.还有一些其他的功能:
·多控件注解
@BindViews({R.id.tv_future1_date, R.id.tv_future2_date, R.id.tv_future3_date,
R.id.tv_future4_date, R.id.tv_future5_date, R.id.tv_future6_date,})
public List<TextView> dates;
· 多事件绑定
@OnClick({R.id.btn_login, R.id.btn_register})
public void login(View view) {
Log.e(TAG, "这里同时绑定了登陆和注册点击事件");
}
· Adapter中绑定
public static class MyViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_msg)
TextView textView;
public LineViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
这里只列举几个,其他的功能可以查看
http://www.cnblogs.com/zhaoyanjun/p/6016341.html
荆轲刺秦王,大功已告成