Android butterknife(Butter Knife)框架是一个注解式编程框架,可以很好的使用@BindView代替findViewById,使用@OnClick代替setOnClickListener等事件,既节约了写代码的时间,也减少了过多的代码量,这也是Java注解式编程的好处,下面来学习一下butterknife框架吧!
1:首先在build.gradle里面导入Butter Knife的jar包,添加如下代码:
implementation 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
如果导入的butterknife版本过新,如butterknife:10.2.3版本,就会报如下错误,所以小编只使用了butterknife:8.8.1作为演示:
Duplicate class android.support.v4.app.INotificationSideChannel found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.app.INotificationSideChannel$Stub found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.app.INotificationSideChannel$Stub$Proxy found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.IResultReceiver found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.IResultReceiver$Stub found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.IResultReceiver$Stub$Proxy found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.ResultReceiver found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.ResultReceiver$1 found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.ResultReceiver$MyResultReceiver found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Duplicate class android.support.v4.os.ResultReceiver$MyRunnable found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:27.1.1)
Go to the documentation to learn how to Fix dependency resolution errors.
2:可以使用@BindView注解绑定一些属性,使用@OnClick绑定点击事件,如下:
绑定属性:
class ExampleActivity extends Activity { @BindView(R2.id.user) EditText username; @BindView(R2.id.pass) EditText password; ... }
绑定点击事件:
@OnClick(R.id.submit) void submit() { // TODO call server... }
当然了,你还可以同时绑定N多个点击事件,代码如下:
@OnClick({R.id.btn_mesage, R.id.btn_image, R.id.btn_list, R.id.btn_dialog1, R.id.btn_dialog2}) public void onClick(View view) { switch (view.getId()) { case R.id.btn_mesage: break; case R.id.btn_image: break; case R.id.btn_list: break; case R.id.btn_dialog1: break; case R.id.btn_dialog2: break; default: break; }
3:butterknife还有一些别的注解,如:@BindColor, @BindString, @BindAnim等,具体的用法可以自己Google一下,如图所示: