JetpackCompose 中 @Preview 的 isInEditMode 模拟

Pet*_*huk 12 android android-jetpack-compose android-jetpack-compose-preview

我正在使用 Jetpack compose 开发一个应用程序,并且在 Jetpack 预览期间遇到字体导入问题。预览为空并显示错误(渲染问题):

Font resource ID #0x... cannot be retrieved
Run Code Online (Sandbox Code Playgroud)

例如,在自定义视图中,我们有一个

isInEditMode
Run Code Online (Sandbox Code Playgroud)

在设计部分控制布局预览,我们可以禁用一些破坏预览的逻辑。

有什么方法可以为 Jetpack @Preview 做到这一点吗?我目前阅读了所有可用的文档/文章,但没有找到答案。

非常感谢您提供任何信息。

Jetpack Compose 代码是:

@Composable
fun ScreenContent() {
    Row(
        modifier = Modifier
            .wrapContentSize()
            .fillMaxWidth()
            .clip(RoundedCornerShape(50))
            .background(colorResource(id = R.color.search_field_background_color)),
        horizontalArrangement = Arrangement.Center
    ) {
        Icon(
            painterResource(id = R.drawable.ic_search_image), contentDescription = stringResource(R.string.search_screen_magnifier_icon_content_description)
        )
        Text(
            modifier = Modifier.padding(all = 8.dp),
            text = stringResource(R.string.search_screen_search_field_text),
            fontSize = 12.sp,
            color = colorResource(id = R.color.search_field_text_color),
            fontFamily = getFont(R.font.nunito_sans_extra_bold)
        )
    }
}

//according to the plan this method will contain
//some flag to return null in @Preview mode
@Composable
private fun getFont(@FontRes fontId : Int): FontFamily? {
    return FontFamily(ResourcesCompat.getFont(LocalContext.current, fontId)!!)
}

@Preview(showSystemUi = true)
@Composable
fun Preview() {
    ScreenContent()
}
Run Code Online (Sandbox Code Playgroud)

Phi*_*hov 21

对于这种情况,Compose 有自己的本地组合值,即LocalInspectionMode. 你可以这样使用它:

@Composable
private fun getFont(@FontRes fontId : Int): FontFamily? {
    if (LocalInspectionMode.current) return null
    return FontFamily(ResourcesCompat.getFont(LocalContext.current, fontId)!!)
}
Run Code Online (Sandbox Code Playgroud)


goo*_*man 2

不幸的是,我也无法找到开箱即用的解决方案,但我想出了一个替代方案。我们可以利用本地组合。这是我试图解决这个问题的尝试:

val LocalPreviewMode = compositionLocalOf { false }

@Composable
fun MyView() {
    if (LocalPreviewMode.current) {
        // render in preview mode
    } else {
        // render normally 
    }
}

@Preview
@Composable
fun PreviewMyView() {
    CompositionLocalProvider(LocalPreviewMode provides true) {
        MyView()
    }
}
Run Code Online (Sandbox Code Playgroud)