I'm trying to build a very simple application with many activities
.
In this app I have a WelcomeActivity
for user to choose his language
with two buttons, one for English
and one for Arabic
then i want after user choose his language , the language will be changing at all activities and this WelcomeActivity
will be run only for the first time and never show again.
any help ?
You can do something like this.
Locale locale = new Locale("ar”,"XX");
private void updateLocale(locale) {
final Configuration configuration = getResources().getConfiguration();
Locale.setDefault(baseLocal);
configuration.locale = baseLocal;
getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
}
How to restore the selected language in next launch.? [ Better to store it in a shared preference.] I hope you might be knowing how to store. You just need to store "ar" or "en" text in preference. On next launch you have to read back and form Locale and pass updateLocale() method.
You can make use OnConfigurationChanged Method
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Configuration configuration = getResources().getConfiguration();
Locale.setDefault(mCurrentLocale);
configuration.locale = mCurrentLocale;..locale from preference or latest selected.
getResources().updateConfiguration(configuration, getResources().getDisplayMetrics());
}
Where mCurrentLocale can be read from shared preference which u stored earlier.
How to store language in shared preference in this case
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
this);
sharedPreferences().putString(KEY_STORE_CURRENT_LOCALE, language_code).commit();
How to get language from shared preference in this case
final String current = sharedPreferences.getString(KEY_STORE_CURRENT_LOCALE,
language_code_english);
I hope this will help!