如何仅为特定XML文件启用Android ViewBinding而非全项目启用
仅对指定XML启用ViewBinding的实现方案
核心逻辑为反向配置生成规则:全局关闭默认全量生成逻辑,仅对需要的布局单独添加启用标记,无需处理无关XML文件,操作成本极低。
1. 模块级构建配置
在对应模块的build.gradle文件中添加如下配置:
Groovy 语法
android { // 开启ViewBinding能力 buildFeatures { viewBinding true } defaultConfig { // 配置默认不生成所有XML的绑定类 manifestPlaceholders["viewBindingIgnore"] = "true" } }
Kotlin DSL 语法
android { buildFeatures { viewBinding = true } defaultConfig { manifestPlaceholders["viewBindingIgnore"] = true } }
2. 给需要的XML添加启用标记
打开需要使用ViewBinding的布局文件,在根节点添加以下属性即可生成对应绑定类:
- 若未声明tools命名空间,先添加:
xmlns:tools="http://schemas.android.com/tools" - 添加启用标记:
tools:viewBindingEnable="true"
示例:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:viewBindingEnable="true"> <!-- 布局内部内容 --> </androidx.constraintlayout.widget.ConstraintLayout>
说明
- 该方案兼容Android Gradle Plugin 4.0及以上版本,无需额外引入依赖
- 仅添加了启用标记的XML会生成绑定类,其余布局完全不参与ViewBinding编译流程,不会增加构建耗时和APK体积
- 绑定类的命名、使用规则和全局开启ViewBinding时完全一致,无适配成本
内容的提问来源于stack exchange,提问作者Sergio
相关产品推荐
相关产品推荐

