setLanguagePreference

fun setLanguagePreference(languageCode: String)

Sets the application locale based on a language code.

This function allows per-app language preferences, independent of the system language. The locale change takes effect immediately and persists across app restarts. All activities are automatically recreated to reflect the new locale.

Supported Language Tags

Use IETF BCP 47 language tags:

  • Simple: "en", "es", "fr", "de", "ja", "zh"

  • With region: "en-US", "en-GB", "es-ES", "es-MX", "zh-CN", "zh-TW"

  • With script: "zh-Hans" (Simplified Chinese), "zh-Hant" (Traditional Chinese)

Usage in ViewModel

@HiltViewModel
class SettingsViewModel @Inject constructor() : ViewModel() {
fun updateLanguage(languageCode: String) {
setLanguagePreference(languageCode)
// Activities will be recreated automatically
}
}

Usage in Settings Screen

@Composable
fun LanguageSelector(onLanguageSelected: (String) -> Unit) {
val languages = listOf(
"en" to "English",
"es" to "Español",
"fr" to "Français",
"de" to "Deutsch"
)

languages.forEach { (code, name) ->
TextButton(onClick = { onLanguageSelected(code) }) {
Text(name)
}
}
}

Behavior

  • Persists across app launches (stored by system)

  • Triggers activity recreation to apply new locale

  • Affects all string resources and date/time formatting

  • Independent of system language setting (API 33+)

Testing Language Changes

@Test
fun testLanguageChange() {
setLanguagePreference("es")
assertEquals("es", getPreferredLocale().language)
}

Parameters

languageCode

IETF BCP 47 language tag (e.g., "en", "es-MX", "zh-Hans")

See also