I am adding a new feature to an android application, that enables the users to switch between two languages.
So far to test out the change of Locale I have been using the following piece of code in one of my Activities.
Locale myLocale = new Locale("ru");
Locale.setDefault(myLocale);
Resources res = this.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
Locale current = getResources().getConfiguration().locale;
if (current.getLanguage().equals(myLocale.getLanguage())){
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
conf.setLocale(myLocale);
createConfigurationContext(conf);
recreate();
}else{
conf.locale = myLocale;
res.updateConfiguration(conf, res.getDisplayMetrics());
recreate();
}
}
setContentView(R.layout.activity_main);
The reason for checking the Version Code is that createConfigurationContext() requires API Level 17 and I'm using API Level 16. So this conditional lets me use the deprecated updateConfiguration() and also the createConfigurationContext().
I have also created the strings.xml for the relevant language and added a few values for testing.
What has been achieved so far is that the Dates are being shown in the translated language, so that tells me that the Locale has actually been changed to the correct one. Other strings that are supposedly taken from strings.xml (ru) aren't changing at all.
Are strings with multiple translations called in a different way from the layout xmls (See code below)? or maybe my structure isn't right?
android:text="@string/upcoming_title"
After posting the question I kept trying some stuff, and decided to try to add the following answer from another post:
https://stackoverflow.com/a/40704077/2199589
This worked as expected.