Search code examples
kotlinandroid-jetpack-compose

how to extract text in a mutableStateOf var? stringResource needs a context


I've got an android app with some text I want to extract into strings.xml to allow for internationalization.

@Composable
fun MainMenu(buttons: List<MenuButtonMessage>, modifier: Modifier = Modifier) {
    var currentTab = rememberSaveable { mutableStateOf("Nothing Selected") }

    Column{
        Row{
            LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.weight(1f))
            {
                items(buttons)
                {
                    b ->
                    MenuButton(b, currentTab)
                }
            }
            Spacer(modifier = Modifier.width(8.dp))
            Text("Select a project"))
        }
        Spacer(modifier = Modifier.height(8.dp))

        Text(currentTab.value)
    }
}

This works, but I've hard-coded the strings. I can use the context actions to "Extract string resource" on the "Select a project" line and that works no problem. But if I do the same for the "Nothing Selected" string I get an error "unresolved reference" on the "context" that Android studio puts in to my mutableStateOf

@Composable
fun MainMenu(buttons: List<MenuButtonMessage>, modifier: Modifier = Modifier) {
    var currentTab = rememberSaveable { mutableStateOf(context.getString(R.string.nothing_selected)) }

    Column{
        Row{
            LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.weight(1f))
            {
                items(buttons)
                {
                    b ->
                    MenuButton(b, currentTab)
                }
            }
            Spacer(modifier = Modifier.width(8.dp))
            Text(stringResource(R.string.select_a_project))
        }
        Spacer(modifier = Modifier.height(8.dp))

        Text(currentTab.value)
    }
}

How can I set the default value of my mutable string to a value from strings.xml?


Solution

  • You'll have to get context manually, like so:

    val context = LocalContext.current
    val currentTab = rememberSaveable { mutableStateOf(context.getString(R.string.nothing_selected)) }