Last active
March 1, 2017 05:18
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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