I need to translate my UI using Kotlin (for Android). I used this code (every time users run the app):
val sharedPref: SharedPreferences = getSharedPreferences(UI_LANGUAGE_CHANGED, PRIVATE_MODE)
var restart: Boolean = sharedPref.getBoolean(UI_LANGUAGE_CHANGED, true)
var lang = selectedLanguageVar.split("-")[0]
if (translations_languages.indexOf(lang) == -1) {
lang = "en"
}
//println("-->sel: " + selectedLanguageVar + " -->lang: " + getString(R.string.language))
//println("-->index: " + translations_languages.indexOf(lang))
var locale: Locale = Locale(lang)
Locale.setDefault(locale)
var res: Resources = resources
var config: Configuration = res.configuration
config.setLocale(locale)
//config.setLayoutDirection(locale)
//createConfigurationContext(config)
resources.updateConfiguration(config, resources.displayMetrics)
if (restart || type == "restart") {
val intent = Intent(this, RestartActivity::class.java).also {
startActivity(it)
finish()
}
} else {
if (type == "start") {
val intent = Intent(this, RestartActivity::class.java).also {
startActivity(it)
}
}
}
but it's translated in the selected language JUST when it is a device language when I installed the app. So, for example, I install the app and on my device there are English and French. If I select one of these two languages, it translate correctly, otherwise it doesn't work.
I tried also createConfigurationContext(config)
but it doesn't work. Is there a way to translate always in a selected language (independently on device)?