依赖注入框架-ButterKnife使用方法总结

ButterKnife

2018-9-6 10:45 - QG2017移动组 - 张艺隽

ButterKnife是JakeWharton大神出品的用于View的注入框架。提供注解来简单快捷地完成View的绑定、点击事件的分离等。


  • 来自官方的说明:

Field and method binding for Android views which uses annotation processing to generate boilerplate code for you.

- Eliminate findViewById calls by using @BindView on fields.
- Group multiple views in a list or array. Operate on all of them at once with actions, setters, or properties.
- Eliminate anonymous inner-classes for listeners by annotating methods with @OnClick and others.
- Eliminate resource lookups by using resource annotations on fields.
Remember: A butter knife is like a dagger only infinitely less sharp.

非常有意思的一句话,这里的匕首指的是Android的另一个主流的依赖注入框架Dagger

0. 参考资料

Android Butterknife使用方法总结

Android studio 插件无法下载(完美解决)

1. 开始使用

  1. 导入依赖:
dependencies {
  implementation 'com.jakewharton:butterknife:8.8.1'
  annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
}
如果使用Kotlin,则将**annotationProcessor**替换为**kapt** 2. 如果不需要在library中使用ButterKnife,则**直接跳过以下步骤。** - 修改buildscript:
buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
  }
}
  • 需要gradle降级
classpath 'com.android.tools.build:gradle:3.0.1'
  • 在module上方加入:
apply plugin: 'com.jakewharton.butterknife'
  • 确保R全部替换为R2
class ExampleActivity extends Activity {
   
    @BindView(R2.id.user) EditText username;
    @BindView(R2.id.pass) EditText password;
}

2. zelezny插件

  1. 安装:zelezny是编译器层面的插件,用于辅助ButterKnife,提供快捷方法来绑定控件。在AS的Setting中找到Plugins,然后搜索插件:zelezny,安装后重启AS。
  2. 使用:
setContentView(R.layout.acty_login)

将鼠标移到acty_login上,右键选择Generate(或Alt+Insert),点击选项Generate ButterKnife Injecttions即可。

3. @BindView

@BindView注解是ButterKnife中最基本的用法,先观看源码:

@Retention(CLASS) @Target(FIELD)
public @interface BindView {
   
  /** View ID to which the field will be bound. */
  @IdRes int value();
}

@IdRes注解指定@BindView的参数为一个控件资源。

  • Java

    1. 在Activity的setContentView后使用ButterKnife.bind(this)
    2. 在方法外部使用注解@BindView()绑定控件。绑定的控件不能被private或static修饰。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值