Skip to content

Instantly share code, notes, and snippets.

@alhazmy13
Last active March 1, 2017 05:18
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alhazmy13/d360b443728f6cac8b5d1038e65f2ce1 to your computer and use it in GitHub Desktop.
Save alhazmy13/d360b443728f6cac8b5d1038e65f2ce1 to your computer and use it in GitHub Desktop.
This class is used to change your application locale and save this change for the next time.
/**
* Created by Alhazmy13 on 11/6/16.
*/
public class LocalUtility {
private static final String SAVED_LANG = "LOCALE_SAVED_LANG";
public static void onCreate(Context context) {
String lang = getSavedData(context, Locale.getDefault().getLanguage());
setLocale(context, lang);
}
public static void onCreate(Context context, String defaultLanguage) {
String lang = getSavedData(context, defaultLanguage);
setLocale(context, lang);
}
public static String getLanguage(Context context) {
return getSavedData(context, Locale.getDefault().getLanguage());
}
public static void setLocale(Context context, String language) {
save(context, language);
updateConfiguration(context, language);
}
private static String getSavedData(Context context, String defaultLanguage) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(SAVED_LANG, defaultLanguage);
}
private static void save(Context context, String language) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(SAVED_LANG, language);
editor.apply();
}
private static void updateConfiguration(Context context, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Resources resources = context.getResources();
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment