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

Android仿butterKnife,练习APT技术(一)_架构师

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

Android仿butterKnife,练习APT技术(一)_架构师_02

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

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

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

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

最后

如果想要成为架构师或想突破20~30K薪资范畴,那就不要局限在编码,业务,要会选型、扩展,提升编程思维。此外,良好的职业规划也很重要,学习的习惯很重要,但是最重要的还是要能持之以恒,任何不能坚持落实的计划都是空谈。

如果你没有方向,这里给大家分享一套由阿里高级架构师编写的《Android八大模块进阶笔记》,帮大家将杂乱、零散、碎片化的知识进行体系化的整理,让大家系统而高效地掌握Android开发的各个知识点。

Android仿butterKnife,练习APT技术(一)_架构师_06