Compose Preview
为 Jetpack Compose 函数创建预览。
基本用法
kotlin1@Preview 2@Composable 3private fun XxxPreview() { 4 AppTheme { 5 Xxx() 6 } 7}
@Preview 注解参数
| 参数 | 说明 | 示例 |
|---|---|---|
name | 预览名称 | @Preview(name = "Dark Mode") |
group | 分组名称 | @Preview(group = "Buttons") |
widthDp | 宽度 (dp) | @Preview(widthDp = 320) |
heightDp | 高度 (dp) | @Preview(heightDp = 640) |
showBackground | 显示背景 | @Preview(showBackground = true) |
backgroundColor | 背景色 (ARGB Long) | @Preview(backgroundColor = 0xFFFFFFFF) |
showSystemUi | 显示系统 UI | @Preview(showSystemUi = true) |
device | 设备规格 | @Preview(device = "id:pixel_5") |
uiMode | UI 模式 | @Preview(uiMode = Configuration.UI_MODE_NIGHT_YES) |
locale | 语言 | @Preview(locale = "zh-rCN") |
fontScale | 字体缩放 | @Preview(fontScale = 1.5f) |
wallpaper | 壁纸 | @Preview(wallpaper = Wallpapers.GREEN_DOMINATED_EXAMPLE) |
Multipreview 注解
创建自定义多预览注解以复用配置:
kotlin1@Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO) 2@Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) 3annotation class ThemePreviews 4 5@Preview(name = "Phone", device = "spec:width=411dp,height=891dp") 6@Preview(name = "Tablet", device = "spec:width=1280dp,height=800dp,dpi=240") 7annotation class DevicePreviews
使用:
kotlin1@ThemePreviews 2@DevicePreviews 3@Composable 4private fun MyComponentPreview() { 5 AppTheme { 6 MyComponent() 7 } 8}
设备规格
预定义设备
id:pixel_5,id:pixel_fold,id:pixel_tabletid:wearos_small_round,id:wearos_large_round
自定义规格
kotlin1@Preview(device = "spec:width=411dp,height=891dp,dpi=420") 2@Preview(device = "spec:width=1280dp,height=800dp,orientation=landscape")
项目约定
- Preview 函数命名:
XxxPreview或PreviewXxx - 使用 AppTheme: 始终用
AppTheme { }包裹预览内容 - 私有函数: Preview 函数应为
private - Mock 数据: 使用假数据填充预览,不依赖 ViewModel
- 放置位置: 在同一文件中,放在被预览组件下方
工作流程
- 找到需要预览的 Composable 函数
- 分析其参数,确定需要的 mock 数据
- 在函数下方创建 Preview 函数
- 用
NeoDBYouTheme包裹 - 根据需要添加多个
@Preview变体(亮/暗主题、不同尺寸等),大多数情况下Preview不需要参数。
示例
简单组件预览
kotlin1@Composable 2fun Greeting(name: String, modifier: Modifier = Modifier) { 3 Text(text = "Hello $name!", modifier = modifier) 4} 5 6@Preview(showBackground = true) 7@Composable 8private fun GreetingPreview() { 9 AppTheme { 10 Greeting("Android") 11 } 12}
状态变体预览
kotlin1@Preview(name = "Empty") 2@Preview(name = "Loading") 3@Preview(name = "Content") 4@Composable 5private fun MyScreenPreview() { 6 AppTheme { 7 // 根据需要展示不同状态 8 } 9}
亮暗主题预览
kotlin1@PreviewLightDark 2@Composable 3private fun CardPreview() { 4 AppTheme { 5 MyCard(title = "Sample", content = "Preview content") 6 } 7}