Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 SnapContextWrapper(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 = DriverPreferenceUtil.getInstance().getString(DriverConstants.PARAM_LANGUAGE, "en");
super.attachBaseContext(SnapContextWrapper.wrap(newBase, language));
}
Call this activity Lifecycle method in the Activity.
@ankit-agg

This comment has been minimized.

Copy link

ankit-agg commented Dec 12, 2018

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.