Reputation: 145
I'm trying to change my application language in runtime. I have checked several posts and my code now looks like:
if(position == 0){//Position 0 of an array to select the language
val locale = Locale("es_ES")
val config = applicationContext.resources.configuration
config.setLocale(locale)
applicationContext.createConfigurationContext(config)
}
I have a values-es directory where I have my own strings.xml file with strings translated. Anyway, it seems like it doesn't change anything.
I repeat I tried and checked a lot of posts in Stack Overflow but I don't know where I'm failing. Thanks in advance, I'm open to any question due to my bad english.
Second try:
I've been tryng and now my code looks like this:
val locale = Locale("es")
Locale.setDefault(locale)
val config = applicationContext.resources.configuration
config.setLocale(locale)
applicationContext.resources.configuration.setTo(config)
Log.d("Configuration",config.toString())
Log.d("Language",config.locales.toLanguageTags())
And the debug messages are :
D/Configuration: {1.0 310mcc260mnc [es] ldltr sw411dp w683dp h387dp 420dpi nrml land finger qwerty/v/v -nav/h winConfig={ mBounds=Rect(0, 0 - 1794, 1080) mAppBounds=Rect(0, 0 - 1794, 1080) mWindowingMode=fullscreen mActivityType=undefined} s.40}
D/Language: es
But my strings doesn't change and my app keeps using the strings(en) file.
Upvotes: 1
Views: 164
Reputation: 1482
Please try this code
String languageToLoad = "es"; // your language
Locale locale = new Locale(languageToLoad);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
Intent refresh = new Intent(DashboardActivity.this, DashboardActivity.class);
startActivity(refresh);
finish();
Upvotes: 1