Android仿butterKnife,练习APT技术(一)

202 阅读1分钟

butterKnife的集成:

在module的build.gradle文件dependencies 中添加以下两个依赖库:

dependencies {
  implementation 'com.jakewharton:butterknife:10.2.3'
  annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
}

如果使用的是kotlin, 使用kapt代替annotationProcessor

Library projects
To use Butter Knife in a library, add the plugin to your buildscript:

buildscript {
  repositories {
    mavenCentral()
    google()
  }
  dependencies {
    classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.3'
  }
}

and then apply it in your module:

apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife' //应用插件

Now make sure you use R2 instead of R inside all Butter Knife annotations.

butterKnife一度节省了findViewById的很多时间,但是当项目中大量使用之后,突然有一天需要改造代码,作为一个库模块使用的时候,就有的哭了,把所有R替换为R2的过程也是要手动修改一个一个文件的,会花费大量的时间,随着DataBinding的出现,以及组件化模式的流行,butterKnife逐渐被弃用了,慎用(坑多)不过可能在一些老的需要维护的项目还是能见到,框架整体设计思想还是值得学习的。

butterKnife的使用过程:

1.声明变量,并在变量上使用注解

@BindView(R.id.sample_text)
TextView textView;

2.调用ButterKnife.bind(this)

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this); //使用textView之前bind,控件的初始化赋值都在这里面
        textView.setText(stringFromJNI());
    }

3.sync project 后会自动生成一个类,命名为类名_ViewBinding

同时会编译该类,生成字节码文件:

看下什么时候使用该类:点击ButterKnife.bind方法

👀关注公众号:Android老皮!!!欢迎大家来找我探讨交流👀