public void loadLocale() {
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs",
Activity.MODE_PRIVATE);
String language = prefs.getString(langPref, "");
changeLang(language);
}
public void changeLang(String lang) {
if (lang.equalsIgnoreCase(""))
return;
myLocale = new Locale(lang);
saveLocale(lang);
Locale.setDefault(myLocale);
android.content.res.Configuration config = new android.content.res.Configuration();
config.locale = myLocale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());
}
public void saveLocale(String lang) {
String langPref = "Language";
SharedPreferences prefs = getSharedPreferences("CommonPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(langPref, lang);
editor.commit();
}
و في ()onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_change_language);
loadLocale();
}
أو:
SharedPreferences sharedPref = getActivity().getPreferences(MY_PREFS_NAME,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("lang", language);
editor.commit();
لتحصل على ال sharedprefrence:
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
MY_PREFS_NAME, Context.MODE_PRIVATE);
String language = sharedPref.getString("lang", null);
يمكنك الاستعانة بالمرجع التالي:SharedPreferences reference
او الدرس التالي:sharedPreference tutorial