Skip to main content

Usage

Prerequisite: Make sure you’ve installed and initialized the Tolgee for Compose. See: Jetpack Compose Installation

Tolgee’s Jetpack Compose extensions let you fetch localized strings directly inside your composables. Below are the most common patterns you’ll use:

  • Use stringResource for simple strings - retrieve a translation by its resource ID.
@Composable
fun SimpleText() {
Text(text = stringResource(R.string.welcome_message))
}
  • Pass parameters to translations - supply arguments for placeholders in your strings.
@Composable
fun TextWithParameters(name: String) {
Text(text = stringResource(R.string.welcome_user, name))
}
  • Handle plurals with pluralStringResource - provide the count and any formatting args.
@Composable
fun PluralText(count: Int) {
Text(text = pluralStringResource(R.plurals.item_count, count, count))
}

Explicit Tolgee Instance

If you need to use a specific Tolgee instance (not the singleton), you can pass it explicitly:

@Composable
fun ExplicitInstance() {
val tolgee = remember { myCustomTolgee }

Text(text = stringResource(tolgee, R.string.welcome_message))
}

Locale Switching

You can create a locale switcher component:

@Composable
fun LocaleSwitcher() {
val tolgee = Tolgee.instance
val locale by tolgee.changeFlow
.map { tolgee.getLocale() }
.collectAsState(initial = tolgee.getLocale())

Row {
Text(text = stringResource(tolgee, R.string.selected_locale, locale.language))
Button(onClick = { tolgee.setLocale("en") }) {
Text("English")
}
Button(onClick = { tolgee.setLocale("fr") }) {
Text("Français")
}
Button(onClick = { tolgee.setLocale("cs") }) {
Text("Čeština")
}
}
}

Observing Locale Changes

Collecting Tolgee.changeFlow as state ensures your composable recomposes whenever the locale changes, keeping the UI in sync with the active language.

@Composable
fun LocaleAwareComponent() {
val tolgee = Tolgee.instance

val locale by tolgee.changeFlow
.map { tolgee.getLocale() }
.collectAsState(initial = tolgee.getLocale())

Text(text = locale.language)
}

Next steps