Skip to content

Instantly share code, notes, and snippets.

@nfaycel
Forked from sud007/MyContextWrapper.java
Created September 22, 2022 13:07
Show Gist options
  • Save nfaycel/0d359e0902e3ea978321fa960a71b169 to your computer and use it in GitHub Desktop.
Save nfaycel/0d359e0902e3ea978321fa960a71b169 to your computer and use it in GitHub Desktop.
A simple gist to demonstrate How to change the App Language in Android.
public class MyContextWrapper extends ContextWrapper {
public MyContextWrapper(Context base) {
super(base);
}
@SuppressWarnings("deprecation")
public static ContextWrapper wrap(Context context, String language) {
Configuration config = context.getResources().getConfiguration();
Locale sysLocale = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
sysLocale = getSystemLocale(config);
} else {
sysLocale = getSystemLocaleLegacy(config);
}
if (!language.equals("") && !sysLocale.getLanguage().equals(language)) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
setSystemLocale(config, locale);
} else {
setSystemLocaleLegacy(config, locale);
}
context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics());
}
return new MyContextWrapper(context);
}
@SuppressWarnings("deprecation")
public static Locale getSystemLocaleLegacy(Configuration config) {
return config.locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static Locale getSystemLocale(Configuration config) {
return config.getLocales().get(0);
}
@SuppressWarnings("deprecation")
public static void setSystemLocaleLegacy(Configuration config, Locale locale) {
config.locale = locale;
}
@TargetApi(Build.VERSION_CODES.N)
public static void setSystemLocale(Configuration config, Locale locale) {
config.setLocale(locale);
}
}
@Override
protected void attachBaseContext(Context newBase) {
//fetch from shared preference also save to the same when applying. default is English
String language = MyPreferenceUtil.getInstance().getString(MyConstants.PARAM_LANGUAGE, "en");
super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}
Call this activity Lifecycle method in the Activity.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment