第三方开源库之 Butter Knife 配置和使用

目前最新版本是 10.2.0。
官网:http://jakewharton.github.io/butterknife/
GitHub:https://github.com/JakeWharton/butterknife

配置

  1. 在 app/build.gradle 中添加如下:
compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

-----------------------------------------
    //Butter Knife
    implementation 'com.jakewharton:butterknife:10.2.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.0'
  1. 在 project/build.gradle 中添加 classpath 如下:
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.0'

使用

  1. 在 Activity 中绑定
class ExampleActivity extends Activity {
  @BindView(R.id.title) TextView title
  @BindView(R.id.subtitle) TextView subtitle;
  @BindView(R.id.footer) TextView footer;
 
  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}
  1. click 事件
@OnClick(R.id.submit)
public void submit() {
  // TODO submit data to server...
}
  1. 绑定ViewHolder
static class ViewHolder {
    @BindView(R.id.title) TextView name;
    @BindView(R.id.job_title) TextView jobTitle;
 
    public ViewHolder(View view) {
      ButterKnife.bind(this, view);
    }
  }
  1. 绑定资源
class ExampleActivity extends Activity {
@BindString(R.string.title) String title;
@BindDrawable(R.drawable.graphic) Drawable graphic;
@BindColor(R.color.red) int red; // int or ColorStateList field
@BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field
  // ...
}
  1. 代码混淆
-keep class butterknife.** { *; }  
-dontwarn butterknife.internal.**  
-keep class **$$ViewBinder { *; }  
  
-keepclasseswithmembernames class * {  
    @butterknife.* ;  
}  
  
-keepclasseswithmembernames class * {  
    @butterknife.* ;  
}

你可能感兴趣的:(第三方开源库之 Butter Knife 配置和使用)