1. 概述
-
ViewBinding 解决了什么问题: ViewBinding 替代 findViewById,更优雅地实现视图交互;
-
ViewBinding 的实现原理: Android Gradle 插件会为每个 XML 布局文件创建一个绑定类,绑定类中包含布局文件中每个定义了
android:id
属性的 View 引用。假设布局文件为fragment_test.xml
,则生成绑定类FragmentTestBinding.java
; -
所有 XML 布局文件都生成 Java 类,会不会导致包体积瞬间增大? 未使用的类会在混淆时被压缩。
2. ViewBinding 与其他视图绑定方案对比
在 ViewBinding 之前,业界已经有过几种视图绑定方案了,想必你也用过。那么,ViewBinding 作为后起之秀就一定比前者香吗,我带你分析下。
角度 | findViewById | ButterKnife | Kotlin Synthetics | DataBinding | ViewBinding | ❓ |
---|---|---|---|---|---|---|
简洁性 | ✖ | ✖ | ✔ | ✔ | ✔ | ❓ |
编译期检查 | ✖ | ✖ | ✖ | ✔ | ✔ | ❓ |
编译速度 | ✔ | ✖ | ✔ | ✖ | ✔ | ❓ |
支持 Kotlin & Java | ✔ | ✔ | ✖ | ✔ | ✔ | ❓ |
收敛模板代码 | ✖ | ✖ | ✔ | ✖ | ✖ | ❓ |
-
简洁性: findViewById 和 ButterKnife 需要在代码中声明很多变量,其他几种方案代码简洁读较好;
-
编译检查: 编译期间主要有两个方面的检查:类型检查 + 只能访问当前布局中的 id。findViewById、ButterKnife 和 Kotlin Synthetics 在这方面表现较差;
-
编译速度: findViewById 的编译速度是最快的,而 ButterKnife 和 DataBinding 中存在注解处理,编译速度略逊色于 Kotlin Synthetics 和 ViewBinding;
-
支持 Kotlin & Java: Kotlin Synthetics 只支持 Kotlin 语言;
-
收敛模板代码: 基本上每种方案都带有一定量的模板代码,只有 Kotlin Synthetics 的模板代码是较少的。
可以看到,并没有一种绝对优势的方法,但越往后整体的效果是有提升的。另外,❓是什么呢?
3. ViewBinding 怎么用?
这一节我们来介绍 ViewBinding 的使用方法,内容不多。
注意:ViewBinding 要求在 Android Gradle Plugin 版本在至少在 3.6 以上。
3.1 添加配置
视图绑定功能按模块级别启用,启用的模块需要在模块级 build.gralde 中添加配置。例如:
build.gradle
android {
…
viewBinding {
enabled = true
}
}
对于不需要生成绑定类的布局文件,可以在根节点声明tools:viewBindingIgnore="true"
。例如:
<LinearLayout
…
tools:viewBindingIgnore=“true” >
…
3.2 创建绑定类
有三个创建绑定类的 API:
fun bind(view :