J
Changing the language for the summer is an interesting task, there are moments. For example, to translate the headlines of the screen, an app will need to be re-intimidated. Example the code that works for API 19+object LocaleUtil {
fun setLocaleFromSettings(baseContext: Context): Context {
val locale = Settings(baseContext).valueLanguage.locale
return if (locale == Language.DEFAULT.locale) {
baseContext
} else {
Locale.setDefault(locale)
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
updateResourcesLocale(baseContext, locale)
} else {
updateResourcesLocaleLegacy(baseContext, locale)
}
}
}
@TargetApi(Build.VERSION_CODES.N)
private fun updateResourcesLocale(context: Context, locale: Locale): Context {
val configuration = Configuration(context.resources.configuration)
configuration.setLocale(locale)
return context.createConfigurationContext(configuration)
}
@Suppress("DEPRECATION")
private fun updateResourcesLocaleLegacy(context: Context, locale: Locale): Context {
val configuration = Configuration(context.resources.configuration)
val displayMetrics = context.resources.displayMetrics
configuration.setLocale(locale)
context.resources.updateConfiguration(configuration, displayMetrics)
return context
}
}
That's how I reset the annex for final translation. private fun triggerRebirth() {
val intent = Intent(baseContext, MainActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
Runtime.getRuntime().exit(0)
}
Enum, where languages are comfortable@Keep
@Suppress("ConstantLocale")
enum class Language(val languageNameResId: Int, val locale: Locale) : SettingsEnum {
DEFAULT(R.string.locale_default, Locale.ENGLISH) {
override fun getResId(): Int {
return languageNameResId
}
},
RUSSIAN(R.string.locale_russian, Locale("ru", "RU")) {
override fun getResId(): Int {
return languageNameResId
}
},
UKRAINIAN(R.string.locale_ukrainian, Locale("uk", "UA")) {
override fun getResId(): Int {
return languageNameResId
}
};
}
It's a prefs where the current chosen locality is stored.Settings(baseContext).valueLanguage.locale
Please note that this decision preserves the automatic choice of language by the system.I also redesigned two methods in application class.override fun attachBaseContext(base: Context?) {
super.attachBaseContext(
base?.let {
LocaleUtil.setLocaleFromSettings(it)
}
)
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
LocaleUtil.setLocaleFromSettings(baseContext)
}