I had some codes for change locale programmatically in Java. But when my application migrated to Kotlin, I can't change locale any more.
For example this code in Java worked very good :
public static final void setAppLocale(String language, Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Resources resources = activity.getResources();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(new Locale(language));
activity.getApplicationContext().createConfigurationContext(configuration);
} else {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = activity.getResources().getConfiguration();
config.locale = locale;
activity.getResources().updateConfiguration(config,
activity.getResources().getDisplayMetrics());
}
}
I tried many codes in Kotlin but non of them worked for me. This is my last try:
fun changeLanguage(context: Context, language : String) {
val locale = Locale(language)
Locale.setDefault(locale)
val config = context.resources.configuration
config.setLocale(locale)
context.createConfigurationContext(config)
context.resources.updateConfiguration(config, context.resources.displayMetrics)
}
How can I change application's local in Kotlin? Old codes that were written in Java did not work in Kotlin application.