在 Android TV 上使用 Jetpack Compose

我们推荐使用 Compose for TV 构建 Android TV 界面。它可为 TV 应用发挥 Android Jetpack Compose 的所有优势,让您可以更轻松地为应用构建功能强大且美观出众的界面。使用 Compose for TV 的一些具体优势如下:

  • 灵活性:Compose 可用于创建任何类型的界面,从简单的布局到复杂的动画。组件开箱即可使用,但也可以根据应用的需求进行自定义和样式设置。
  • 简化和加速开发:Compose 与现有代码兼容,使开发者能够使用更少的代码更高效地构建应用。
  • 直观:Compose 使用声明式语法,让您能够更改界面,以及调试、理解和审核代码。

如果您不熟悉如何使用 Jetpack Compose 工具包,请查看 Compose 开发者在线课程。Compose 移动设备的许多开发原则也适用于 TV。如需详细了解声明式界面框架的一般优势,请参阅为什么采用 Compose。如需了解详情,另请参阅 GitHub 上的 Compose for TV 示例代码库

兼容性

Compose for TV 适用于 API 级别为 21 或更高级别的 Android TV。若要使用 Compose for TV 1.0 版,您需要使用 1.3.0 版 androidx.compose 库和 Kotlin 1.7.10。

设置

在 Android TV 上使用 Jetpack Compose 与将 Jetpack Compose 用于任何其他 Android 项目类似。主要区别在于,Compose for TV 添加的库可提供针对 TV 优化的组件,并可让您更轻松地创建为 TV 量身定制的界面。在某些情况下,这些组件与对应的非 TV 组件同名,例如 androidx.tv.material3.Buttonandroidx.compose.material3.Button

Jetpack Compose 工具包依赖项

如需使用 Compose for TV,您需要在应用的 build.gradle 文件中添加 Jetpack Compose 工具包依赖项,如下所示:

Kotlin

dependencies {
   val composeBom = platform("androidx.compose:compose-bom:2024.06.00")
   implementation(composeBom)

   // General compose dependencies
   implementation("androidx.activity:activity-compose:1.9.0")

   implementation("androidx.compose.ui:ui-tooling-preview")
   debugImplementation("androidx.compose.ui:ui-tooling")

   // Compose for TV dependencies
   implementation("androidx.tv:tv-foundation:1.0.0-alpha10")
   implementation("androidx.tv:tv-material:1.0.0-beta01")
}

Groovy

dependencies {
   def composeBom = platform('androidx.compose:compose-bom:2024.06.00')
   implementation composeBom

   // General compose dependencies
   implementation 'androidx.activity:activity-compose:1.9.0'

   implementation 'androidx.compose.ui:ui-tooling-preview'
   debugImplementation 'androidx.compose.ui:ui-tooling'

   // Compose for TV dependencies
   implementation 'androidx.tv:tv-foundation:1.0.0-alpha10'
   implementation 'androidx.tv:tv-material:1.0.0-beta01'
}

不同之处

尽可能使用 TV 版的 API。 虽然从技术层面来讲,可以使用移动版 Compose Material,但它并没有针对 Android TV 上独特的互动样式进行优化。此外,将 Compose Material 与 Compose for TV 中的 Compose Material 搭配使用可能会导致意外行为。例如,由于每个库都有自己的 MaterialTheme 对象,因此如果同时使用这两个版本,颜色、排版或形状就可能不一致。

下表概述了 TV 和移动设备之间的依赖关系差异:

TV 依赖项
(androidx.tv.*)
比较 移动设备依赖项
(androidx.compose.*)
androidx.tv:tv-material 代替 androidx.compose.material3:material3
androidx.tv:tv-foundation 加上 androidx.compose.foundation:foundation

其他资源

深入阅读

请浏览以下指南,了解如何针对以下平台打造针对电视优化的出色体验: