Android--Butterknife使用方法总结

一、简介

       ButterKnife是一个专注于Android系统的View注入框架,以前总是要写很多findViewById来找到View对象,有了ButterKnife可以很轻松的省去这些步骤。

二、引入

1、在Project的 build.gradle 中添加如下代码:

buildscript {
  repositories {
    mavenCentral()
    google()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.1.0'//添加这行代码
  }
}

2、在App的 build.gradle 中添加如下代码:

apply plugin: 'com.jakewharton.butterknife'

3、在App的 build.gradle dependencies中添加:

implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'

如果遇见Android resource linking failed报错,解决方法:https://blog.csdn.net/chaoyu168/article/details/88770751

三、简单使用

1、在Activity 类中绑定 :ButterKnife.bind(this);必须在setContentView();之后绑定;且父类bind绑定后,子类不需要再bind。

2、在非Activity 类(eg:Fragment、ViewHold)中绑定: ButterKnife.bind(this,view);这里的this不能替换成getActivity()。

3、在Activity中不需要做解绑操作,在Fragment 中必须在onDestroyView()中做解绑操作。

4、使用ButterKnife修饰的方法和控件,不能用private or static 修饰,否则会报错。错误: @BindView fields must not be private or static. (com.zyj.wifi.ButterknifeActivity.button1)

5、setContentView()不能通过注解实现。(其他的有些注解框架可以)

6、使用Activity为根视图绑定任意对象时,如果你使用类似MVC的设计模式你可以在Activity 调用ButterKnife.bind(this, activity),来绑定Controller。

7、使用ButterKnife.bind(this,view)绑定一个view的子节点字段。如果你在子View的布局里或者自定义view的构造方法里 使用了inflate,你可以立刻调用此方法。或者,从XML inflate来的自定义view类型可以在onFinishInflate回调方法中使用它。
 

具体DEMO:https://github.com/chaoyu168/ButterknifeDemo

四、Android studio便捷实用插件Zelezny

Android--Butterknife使用方法总结

插件安装方法:https://blog.csdn.net/chaoyu168/article/details/88077930