ButterKnife实战

93 阅读2分钟

##ButterKnife的作用与示例

View注入库,方便注入View以及注入View的事件,提升开发效率;

Android视图字段和方法的绑定,使用注释处理为开发者生成样板代码(generate boilerplate code);

  • 在相关(View)字段上,消除findViewById的调用,使用@BindView ;
  • 将list或array中的多个view分组。 通过actions, setters, 或者properties一次性完成所有这些操作(分组);
  • 通过使用@OnClick和其他注解标志去注解相关methods(方法函数),来消除listener的匿名内部类。
  • 在字段上,通过使用resource annotations(资源注释)来消除资源查找;

##初始化项目与配置 新建一个Module: Module名输入:然后Next、Next、Finish,完成Module的创建;


#####接着引入ButterKnife

  • 这里有点坑,不是,是很多坑,踩了很多坑;
    ButterKnife现在最新10.1.0版本,要使用的话,需要将项目迁移至 AndroidX,风险也比较大,对于比较大的项目,这条路比较坎坷,入坑慎重。 这里给出官方文档,大家可以自己了解下。
    笔者的AS环境是3.3.1,最终结论是推荐使用 ButterKnife 9.0.0 版本! 项目的 build.gradle 中的配置:
buildscript {
  repositories {
    mavenCentral()
    google()
   }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0'
  }
}

module 中的 build.gradle 中的配置,不要忘记使用 Java 8:

android {
    ....
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
dependencies {
  implementation 'com.jakewharton:butterknife:9.0.0'
  annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0'
}
  • 这篇文章总结了10.1.0/8.8.1/9.0.0等三个版本的引入错误;

##注入TextView、Button、事件 编写activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/btn_test1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Btn1"/>

    <Button
        android:id="@+id/btn_test2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Btn2"/>

</LinearLayout>

编写MainActivity.java:

  • 这里可能由于刚刚加入ButterKnife, AS还没能识别出来,导致编写注解的时候爆红; 这个地方编译一下项目即可,便可以正常使用ButterKnife了;

  • Tip:注解都是可以查看源码的,如果忘了参数的话可以看一下源码,
    比如@OnClick的参数是一个int数组:

0808 0815 0824 0844 0903 0908 0930

0004 0006 0010 0014 绑定资源跟@BindString的用法都一样