从 Kotlin 合成迁移到 Jetpack 视图绑定

Kotlin Android 扩展已被弃用,这意味着使用 Kotlin 合成视图绑定不再受支持。如果您的应用使用 Kotlin 合成技术,请按照本指南迁移到 Jetpack 视图绑定。

如果您的应用尚未使用 Kotlin 合成进行视图绑定,请参阅视图 绑定

更新 Gradle 文件

与 Android 扩展程序一样,Jetpack 视图绑定是逐个模块启用的 基础。对于使用视图绑定的每个模块,请设置 viewBinding build 模块级 build.gradle 文件中的 true 选项:

GroovyKotlin
android {
   
...
    buildFeatures
{
        viewBinding
true
   
}
}
android {
   
...
    buildFeatures
{
        viewBinding
= true
   
}
}

如果您的应用不使用 Parcelable 功能,请移除启用 Kotlin Android 扩展的代码行:

GroovyKotlin
plugins {
  id
'kotlin-android-extensions'
}
plugins {
    kotlin
("android.extensions")
}

如需详细了解如何在模块中启用视图绑定,请参阅设置 操作说明

更新 activity 和 fragment 类

借助 Jetpack 视图绑定,系统会为每个 XML 布局文件生成一个绑定类 模块包含的资源。此绑定类的名称就是 (采用 Pascal 大小写格式,并在末尾添加 Binding 一词)。例如,如果 该布局文件的名称为 result_profile.xml,即生成的 绑定类为 ResultProfileBinding

使用生成的绑定类(而不是合成属性) 引用视图,并通过执行 以下:

  1. kotlinx.android.synthetic 中移除所有导入内容。

  2. 为 activity 膨胀生成的绑定类的实例,或 fragment。

  3. 更改所有视图引用以使用绑定类实例,而不是 合成属性:

// Reference to "name" TextView using synthetic properties.
name
.text = viewModel.nameString

// Reference to "name" TextView using the binding class instance.
binding
.name.text = viewModel.nameString

如需了解详情,请参阅使用部分 请查看视图绑定指南

Discover the latest app development tools, platform updates, training, and documentation for developers across every Android device.

更新于 Dec 22, 2024

Discover the latest app development tools, platform updates, training, and documentation for developers across every Android device.

更新于 Dec 22, 2024

Discover the latest app development tools, platform updates, training, and documentation for developers across every Android device.

更新于 Aug 29, 2024