Skip to content

Instantly share code, notes, and snippets.

@sud007
Last active December 23, 2022 07:46
Show Gist options
  • Save sud007/1dfec39432a04d83c8945f2b448359c7 to your computer and use it in GitHub Desktop.
Save sud007/1dfec39432a04d83c8945f2b448359c7 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.
@ankit-agg
Copy link

return new SnapContextWrapper(context); in line 27 should be return new MyContextWrapper(context);

@sud007
Copy link
Author

sud007 commented May 3, 2020

return new SnapContextWrapper(context); in line 27 should be return new MyContextWrapper(context);

You are right @ankit-GG

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment