Why does Jetpack Compose preview show the wrong string resources?

2.3k Views Asked by At

Sometimes when I use a string resource in my composable, the preview will show the wrong string. It always works fine for literal strings, only string resources are wrong. The bug isn't consistent.

For example if I have this strings.xml:

<resources>
    <string name="app_name">Violit</string>
    <string name="load_topic_failure_message">Something went wrong loading the topic</string>
</resources>

And I have this composable:

@Composable
fun TopicFailureContent() {
    Text(stringResource(R.string.load_topic_failure_message))
}

@Preview(showBackground = true)
@Composable
fun TopicFailureContentPreview() {
    TopicFailureContent()
}

It might render something like "Partially checked" or "Navigation menu" instead of "Something went wrong loading the topic".

If I change the composable to this:

@Composable
fun TopicFailureContent() {
    Text("Something went wrong loading the topic")
}

it renders the preview correctly.

It looks like the preview might be rendering nearby strings instead of the one I want. String resources work fine in tests and running the app. It's just preview that is not always working.

I'm using Android Studio Electric Eel 2022.1.1 but I was having the same problem on the previous version as well. This fails on both Compose UI version 1.2.1 and 1.3.3.

Any idea why string resources don't always work in preview and how to fix it?

1

There are 1 best solutions below

1
On

this problem will appear after editing the resource string file. It solved for me by building the project and then restarting IDE after every edit in resource file.