3

Can i change all the text in my app to other text, when i click a button or maybe select a menu item?

What I am actually trying to do is make my app to translate to a couple of non-iso languages ("non-iso" means i couldn't find them on wiki's ISO-639 list).

So I want the user to be able to select the language in which they view my app, regardless of whatever their phone language settings might be. And i want them to be able to make the language selection from within the app.

I have all the english button and textview text in strings.xml, and i can make a strings-xx.xml for the new languages.

I will be using a submenu with the language options listed. So the text change will be responding to an onclick event on that menu. Any pointers will be very welcome.

GeorgeF
  • 85
  • 1
  • 5

1 Answers1

2

Taken from: How to change language of app when user selects language?

public void setLocale(String lang) { 
    myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, YOURACTIVITY.class); 
    startActivity(refresh); 
    finish();
} 

You cann pass any valid language string to the setLocale method, like "de" or "it", but you have to restart the Activity.

I don't know how your App will behave if you press the back button. If it starts your "old" Activity try this while restarting your Activity:

public void setLocale(String lang) { 
    myLocale = new Locale(lang); 
    Resources res = getResources(); 
    DisplayMetrics dm = res.getDisplayMetrics(); 
    Configuration conf = res.getConfiguration(); 
    conf.locale = myLocale; 
    res.updateConfiguration(conf, dm); 
    Intent refresh = new Intent(this, YOURACTIVITY.class);
    refresh.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(refresh); 

}

Community
  • 1
  • 1
babadaba
  • 814
  • 5
  • 20
  • many thanks for your reply. Apologies for my delayed response. A very dear loved one passed away. Ok, so i have applied your solution and it works well. I also have a loadLocale () method, which i call in my launcher activity's onCreate. the only trouble i am having is that when i close the app and reopen it, i get a blank screen. I have found that when i comment out the loadLocale method, the app loads normally, the locales change ok, but the locale settings don't get saved. Below is the loadLocale() method. changeLanguage() on the last line, is like your setLocale() method, above. – GeorgeF Mar 13 '17 at 12:09
  • `public void loadLocale() { String langPref = "Language"; SharedPreferences prefs = getSharedPreferences("com.georgey.multilanguageapp.PREFERENCES", Context.MODE_PRIVATE); String language = prefs.getString(langPref, ""); changeLanguage(language); }` – GeorgeF Mar 13 '17 at 12:10