10

I am developing an app using Jetpack compose and have a problem with fonts import during Jetpack preview. Preview is empty and show an error (Render problem):

Font resource ID #0x... cannot be retrieved

In custom view for example we have a

isInEditMode

to control layout preview in design section and we are able to disable some logic that ruins preview.

Is any way to do it for Jetpack @Preview ? I currently read all available docs/articles and didn't found the answer.

Would be very appreciate for any info.

The Jetpack Compose code is:

@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()
}
Peter Staranchuk
  • 1,343
  • 3
  • 14
  • 29

2 Answers2

18

Compose has it's own local composition value for this case, which is LocalInspectionMode. You can use it like following:

@Composable
private fun getFont(@FontRes fontId : Int): FontFamily? {
    if (LocalInspectionMode.current) return null
    return FontFamily(ResourcesCompat.getFont(LocalContext.current, fontId)!!)
}
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
2

Unfortunately I also have not been able to find an out of the box solution, but I have come up with an alternative. We can take advantage of local composition. This is my attempt at addressing this:

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()
    }
}
gookman
  • 2,527
  • 2
  • 20
  • 28