现有应用可能包含大量 View 主题和样式。在现有应用中引入 Compose 时,您需要迁移主题才能对 Compose 界面使用 MaterialTheme
。这意味着应用的主题将会有 2 个可信来源:基于 View 的主题以及 Compose 主题。样式上的任何更改都需要在多处实施。
将应用迁移到 Compose 意味着您需要创建现有主题的 Compose 版本。不过,在迁移过程中过早这样做,您就必须同时维护 XML 主题和 Compose 主题,这可能会造成维护负担。
Material Theme Adapter
如果您的应用中使用了 MDC-Android 库中的 Theme.MaterialComponents.*
主题,那么借助 Material Theme Adapter 库,您就可以在可组合项中轻松地重复使用基于 View 的现有 XML 主题中的 Material 2 颜色、排版和形状主题。
使用 MdcTheme
可组合项:
import com.google.accompanist.themeadapter.material.MdcTheme class MdcThemeExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Use MdcTheme instead of M2 MaterialTheme // Colors, typography, and shapes have been read from the // View-based theme used in this Activity setContent { MdcTheme { // Your app-level composable here } } } }
如需了解详情,请参阅 Material Theme Adapter 库文档。
Material 3 Theme Adapter
如果您的应用中使用了 MDC-Android 库中的 Theme.Material3.*
主题,那么借助 Material 3 Theme Adapter 库,您就可以在可组合项中轻松地重复使用基于 View 的现有 XML 主题中的 Material 3 颜色、排版和形状主题。
使用 Mdc3Theme
可组合项:
import com.google.accompanist.themeadapter.material3.Mdc3Theme class Mdc3ThemeExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Use Mdc3Theme instead of M3 MaterialTheme // Color scheme, typography, and shapes have been read from the // View-based theme used in this Activity setContent { Mdc3Theme { // Your app-level composable here } } } }
如需了解详情,请参阅 Material 3 Theme Adapter 库文档。
AppCompat Theme Adapter
借助 AppCompat Theme Adapter 库,您可以在 Jetpack Compose 中轻松地重复使用 AppCompat XML 主题。它会使用上下文主题中的颜色和排版值创建 M2 MaterialTheme
。
使用 AppCompatTheme
可组合项:
import com.google.accompanist.themeadapter.appcompat.AppCompatTheme class AppCompatThemeExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { // Colors and typography have been read from the // View-based theme used in this Activity // Shapes are the default for M2 as this didn't exist in M1 AppCompatTheme { // Your app-level composable here } } } }
如需了解更多信息,请参阅 AppCompat Theme Adapter 库文档。
自定义主题属性
上述所有 Accompanist Theme Adapter 库都使用了 Core Theme Adapter 库,该库包含各种 XML 资源到 Compose 转换的通用逻辑。这些资源实用程序可用于解析自定义主题属性。
如需了解详情,请参阅 Core Theme Adapter 库文档。
默认组件样式
Accompanist Theme Adapter 库不会读取任何由主题定义的默认 widget 样式。这是因为 Compose 没有默认可组合项的概念。
如需了解更多信息,请参阅 Compose 中的自定义设计系统。
主题叠加层
将基于 View 的屏幕迁移到 Compose 时,请注意 android:theme
属性的用法。您可能需要在 Compose 界面树的相应部分添加新的 MaterialTheme
。