Google Rally示例中RallyAlertDialog组件Jetpack Compose Preview不显示无报错
问题原因及解决方法
核心原因
Jetpack Compose 自带的AlertDialog属于窗口级弹出组件,默认预览环境不会直接渲染这类依附于窗口的悬浮组件,同时你的预览代码缺少项目基础主题的包裹,也会导致RallyDialogThemeOverlay无法读取到正确的MaterialTheme配置,最终渲染失败且无报错。
具体解决步骤
- 方法1:适配高版本Android Studio(Hedgehog及更高版本)
调整@Preview参数,同时在预览函数外层包裹项目的基础Rally主题,调整后代码如下:@Preview(showBackground = true, showSystemUi = true) @Composable fun PreviewRallyAlertDialog() { // 外层包裹项目基础主题,确保RallyDialogThemeOverlay能读取到正确的主题配置 RallyTheme { val alertMessage = "Heads up, you've used up 90% of your Shopping budget for this month." val buttonText = "Dismiss".uppercase(Locale.getDefault()) RallyAlertDialog( onDismiss = { /*TODO*/ }, bodyText = alertMessage, buttonText = buttonText ) } } - 方法2:低版本Android Studio兼容方案
把AlertDialog的内容抽成独立可组合项,直接预览抽离后的内容,避开Dialog组件本身的预览限制,代码调整示例:- 抽离Dialog内容逻辑:
@Composable fun RallyAlertDialogContent( onDismiss: () -> Unit, bodyText: String, buttonText: String ) { Column(modifier = Modifier.width(300.dp)) { Text(bodyText, modifier = Modifier.padding(16.dp)) Divider( Modifier.padding(horizontal = 12.dp), color = MaterialTheme.colors.onSurface.copy(alpha = 0.2f) ) TextButton( onClick = onDismiss, shape = RectangleShape, contentPadding = PaddingValues(16.dp), modifier = Modifier.fillMaxWidth() ) { Text(buttonText) } } }- 原
RallyAlertDialog复用抽离的内容:
@Composable fun RallyAlertDialog( onDismiss: () -> Unit, bodyText: String, buttonText: String ) { RallyDialogThemeOverlay { AlertDialog( onDismissRequest = onDismiss, text = { Text(bodyText) }, buttons = { RallyAlertDialogContent(onDismiss, bodyText, buttonText) } ) } }- 预览代码直接预览抽离后的内容:
@Preview(showBackground = true) @Composable fun PreviewRallyAlertDialog() { RallyTheme { val alertMessage = "Heads up, you've used up 90% of your Shopping budget for this month." val buttonText = "Dismiss".uppercase(Locale.getDefault()) RallyAlertDialogContent( onDismiss = { /*TODO*/ }, bodyText = alertMessage, buttonText = buttonText ) } }
内容的提问来源于stack exchange,提问作者lbarqueira
相关产品推荐
相关产品推荐

