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.
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
final Configuration LANG_CONFIG = ChooseLocale.this.getResources().getConfiguration();
Locale newLocale = new Locale("English");
curLang = ChooseLocale.this.getLanguage();
if ((curLang.equals("English")) || (curLang.equalsIgnoreCase("Ingles")))
{
newLocale = new Locale("en_US");
}
else
{
newLocale = new Locale("es");
}
Toast.makeText(getApplicationContext(), newLangToast + " " + curLang , Toast.LENGTH_SHORT).show();
Configuration config = getBaseContext().getResources().getConfiguration();
Locale.setDefault(newLocale);
config.locale = newLocale;
getBaseContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
SharedPreferences.Editor editor = 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
#Override
public void onConfigurationChanged(Configuration newConfig) {
newConfig = Globals.getUserLanguage(this);
super.onConfigurationChanged(newConfig);
to every activity that allows orientation change and add this to my onCreate() of each
final SharedPreferences langPref = 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
Related
Following is the Application code of my Android app:
public class MyApplication extends Application
{
private Locale locale = null;
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (locale != null)
{
newConfig.locale = locale;
Locale.setDefault(locale);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
}
}
#Override
public void onCreate()
{
super.onCreate();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();
String lang = settings.getString(getString(R.string.pref_language), "");
if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
{
locale = new Locale(lang);
Log.i("Locale" , lang);
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
}
}
I have got to change the value of settings.getString(getString(R.string.pref_language), ""); from the Settings Activity of my app.
The problem is none of the strings (which have a translation) and are accessed using getString() method, are showing the translated text.
EDIT1 : I am using Android 8.0
In android 8, the behavior of the Locales changed, now every Activity context will take its locale, i.e if you in Activity1 and changed the locale for Activity1, then Activity2 will remain on the default locale.
The solution is to change the locale for every Activity and your issue will be fixed.
When you are using getString(R.string.pref_language) the call will return the string from the language matching Locale.getDefault() as long as a translation is provided.
If a translation is not provided it will return the default language, that is the language your using in the values/strings.xml file.
All translated values are in values-xx folders, where xx is the 2 letter ISO code for the language.
I know how to use locale and strings.xml for global locale, in addition I created 3 buttons on rhe main activity with 3 different languages on them, how can I switch the whole strings in all screens in one click, how can I do that?
Step1:
Use a preference to store the locale language and country, if you want this language switching is persistent.
Step2:
Try a function like this
public void switchLocale(Locale locale) {
Configuration config = getBaseContext().getResources().getConfiguration();
if (locale != null && !config.locale.equals(locale)) {
Locale.setDefault(locale);
Configuration conf = new Configuration(config);
conf.locale = locale;
getBaseContext().getResources().updateConfiguration(conf,
getBaseContext().getResources().getDisplayMetrics());
}
}
Step3:
Restart your current activity.
Hope this helps.
My android application is in dual language. So I have 2 res folder value and value-sw(for swahili). I am fetching string values from this file in design and also at run time. For example in layout:
android:hint="#string/Officer"
and in code:
getResources().getString(R.string.Officer);
To change the locale setting I have function which I call on onCreate() which looks like this:
public void ChangeLanguage(Context ctx,String Language){
Resources res = ctx.getResources();
DisplayMetrics dm = res.getDisplayMetrics();
android.content.res.Configuration config = res.getConfiguration();
config.locale = new Locale(Language.toLowerCase());
res.updateConfiguration(config, dm);
}
All works fine. Problem comes only if I change the orientation.
For example on start up I set the language to Swahili. So everything is in Swahili. Now if I change the orientation from vertical to horizontal or vice-verse. Textbox box hint which was set in layout remains in Swahili which I expect. But getResources().getString(R.string.Officer); fetches value from the default value file, which is English.
Any suggestions?
Set android:configChanges="orientation" to your activity in AndroidManifest.xml
Doing so will cause your activity not to be destroyed and re-created when orientation is changed.
The problem with having the android:configChanges attribute, is that that disables onCreate() from being called after an orientation change. You are basically telling the app: "I know there will be orientation changes, so don't recreate the screen, I will handle it"
I would suggest calling that function of yours in the onConfigurationChanged() method. Have in mind that any views will be null at that point, so if you need them you will need to get a new reference.
I have same case as one in the question, using English and Swahili in an app.
This is how I tackled it : I created a folder called values-sw then in the folder I created a resource file named string.xml. this is where all my Swahili translations are written. I call the following method in onCreate:
public static void setLocale(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);
String userLocale = sharedPreferences.getString("userlocale", null); // adapt to your need
if (userLocale != null) {
Locale locale = new Locale(userLocale);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
}
Dont forget to refresh your activity for changes to take effect:
finish();
startActivity(getIntent());
(I know it's pretty late for this answer I hope it helps someone out there, cheers!)
I would like the application language to be set according to the user preferences but up till now it doesn't work how I would like it to.
I have set the default values: strings.xml and also values-es with a strings.xml inside in spanish. I have a menu option which brings the user to a Preference activity where he can amon gother things chose the language.
So here are some extracts of the code:
public class Preference extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
......
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
...}
//(......)
//and here I have the listener so when the language pref changes value the locale gets changed.
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("listPref2")) {
String idioma = sharedPreferences.getString("listPref2", "catala");
if ("castella".equals(idioma)) {
idioma = "es_ES";
Locale locale = new Locale(idioma);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getApplicationContext().getResources().updateConfiguration(config,
getBaseContext().getResources().getDisplayMetrics());
}
}
}
So when I change the language it works but then when I come back later or restart the emulator the language gets back to default locale the en_US and the app language gets changed back to default again. What can I do to sort that out?
I know I can get this preference (which I can access to from all my activities) and then each time set up the locale but I find it a bit heavy isn't there a way to do it in a more elegant way?
What I would like to do is if the user sets up the language so when he comes back 2 days later he doesn't have to change the language again.
Any ideas?
OK it may help someone. I have added the folowing to the main activity manifest:
android:configChanges="locale"
Then when the user choses the preferences I have put a confirm button and then this button brings you to main activity that is why the lnagages gets reset.
I have a static class where I have this code to change the locale:
public static void updateLanguage(Context context, String idioma) {
if (!"".equals(idioma)) {
if ("castella".equals(idioma)) {
idioma = "es_ES";
} else if ("catala".equals(idioma)) {
idioma = "ca_ES";
}
Locale locale = new Locale(idioma);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
context.getResources().updateConfiguration(config, null);
}
}
end at every activity I have like 20 of them I call this method before:
setContentView(R.layout.list_event);
With these methods when I rotate the screen the activities don't change the language
here is a link to a blog that helped me:
http://adrianvintu.com/blogengine/post/Force-Locale-on-Android.aspx
I would think that you need to be setting the locale in the MainActivity onCreate method. The same way you are setting it when the onSharedPreferenceChanged method.
I want to rotate my phone and keep the locale. I have folders values, values-en and values-hr. In every activity I have
android:configChanges="keyboardHidden|orientation|locale"
and in every activity.java file I have
private Locale locale = null;
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (locale != null)
{
newConfig.locale = locale;
Locale.setDefault(locale);
getBaseContext().getResources().updateConfiguration(newConfig, getBaseContext().getResources().getDisplayMetrics());
}
}
and in onCreate
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Configuration config = getBaseContext().getResources().getConfiguration();
String lang = settings.getString("language","en");
if (! "".equals(lang) && ! config.locale.getLanguage().equals(lang))
{
locale = new Locale(lang);
Locale.setDefault(locale);
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
}
It works till I rotate my phone - app is still working, buttons and everything is fine - but locale is getting weird - sometimes it's my locale (hr) sometimes it's (en)...
What else I need to add?
I simply removed "if's" and everything is working now. Yes, it is a little "bulky" every time to "re-force" a locale but I couldn't find another way.
My solution is a little bit different, I just "re-force" it on onCreate and onConfigChange - not every 100ms or so and on Desire (2.2) it's working flawlessly.
#Austyn
Yes, it's pretty much the same question but I though is there another solution except "100ms forcing".
#Mayra
Users wanna have their mother-tongue (HR) but it's not supported in (current) mobile phones so this is the only way - to force it =/