Skip to content Skip to sidebar Skip to footer

Android Localization From External Xml

Is it possible to translate android application at runtime using XML received from service? If it is possible could someone please point me in right direction. Thank you.

Solution 1:

Warning

Everything I have read says that its not a good idea to let your app change the language because it isn't supported by the Android framework and it may cause problems.

With that being said, I have done it in my app and, while it has been a bit of a pain, it seems to be working so far. Here is how I did it in case you want to do it this way. You need a separate strings.xml file for each language. strings.xml in values folder as your default then maybe a strings.xml in say a values-es folder for Spanish strings. I have used the following code to change the configuration settings depending on a RadioButton that the user selects

finalConfigurationLANG_CONFIG= ChooseLocale.this.getResources().getConfiguration();
LocalenewLocale=newLocale("English");
curLang = ChooseLocale.this.getLanguage();
if ((curLang.equals("English")) || (curLang.equalsIgnoreCase("Ingles")))
{
    newLocale = newLocale("en_US");
}
else
{
    newLocale = newLocale("es");
}
Toast.makeText(getApplicationContext(), newLangToast + " " + curLang , Toast.LENGTH_SHORT).show();
Configurationconfig= getBaseContext().getResources().getConfiguration();
Locale.setDefault(newLocale);
config.locale = newLocale;
getBaseContext().getResources().updateConfiguration(config, 
        getBaseContext().getResources().getDisplayMetrics());

SharedPreferences.Editoreditor= langPref.edit();
editor.putString(LANG_PREF, curLang);
editor.commit();

With this line being the most important to update the config

getBaseContext().getResources().updateConfiguration(config, 
        getBaseContext().getResources().getDisplayMetrics());

I get the locale from my getLanguage() function which can be handled however you want. I also had to add

@OverridepublicvoidonConfigurationChanged(Configuration newConfig) {
    newConfig = Globals.getUserLanguage(this);
    super.onConfigurationChanged(newConfig);

to every activity that allows orientation change and add this to my onCreate() of each

finalSharedPreferenceslangPref= getSharedPreferences (LANG_PREF, 0);
if (Globals.langConfig != null)
    this.onConfigurationChanged(Globals.langConfig);

I also added android:configChanges="orientation|locale" to each activity in the manifest that allows orientation change

Android Docs on localization

Post a Comment for "Android Localization From External Xml"