How can I change default string.xml? I can change my app to five different languages, but whenever I close the app and reopen it. It goes back to default English.
Is
You can try this:
To Change:
public void changeLanguage(String language) {
locale = new Locale(language);
saveLocale(language);
Locale.setDefault(locale);
conf.locale = locale;
getBaseContext().getResources().updateConfiguration(conf, null);
updateText();
}
To Save:
public void saveLocale(String language) {
SharedPreferences sharedPreferences = getSharedPreferences("com.example.myapp.PREFERENCES", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("USER_LANGUAGE", language);
editor.commit();
}
To Update:
private void updateText() {
btn_chat.setText(R.string.live_chat);
}
To Load:
public void LoadLanguage(){
SharedPreferences shp = getSharedPreferences(
"com.example.myapp.PREFERENCES",Context.MODE_PRIVATE);
String language = shp.getString("USER_LANGUAGE","");
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
}
In MainActivity you can check the default language that app is using:
language = getResources().getString(R.string.lang);
Then if the language is the language you want by check with statement, you should perform updateText()
function:
if (language.equals("zh")) {
btn_lang.setText(R.string.someName);
updateText();
}
Do not forget to perform the LoadLanguage()
in MainActivity to Load the language that user saved.