Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Android TimePicker with custom Locale.
public class LocaleTimePicker extends TimePicker {
public LocaleTimePicker(Context context) {
this(context, null);
}
public LocaleTimePicker(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, Resources.getSystem().getIdentifier("timePickerStyle", "attr", "android"));
}
public LocaleTimePicker(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(new ContextLocaleWrapper(context, getLocaleFromAttrs(context, attrs, defStyleAttr), true), attrs, defStyleAttr);
((ContextLocaleWrapper) getContext()).resetDefaultLocale();
}
private static @Nullable Locale getLocaleFromAttrs(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LocaleTimePicker, defStyleAttr, 0);
String lang = a.getString(R.styleable.LocaleTimePicker_locale);
a.recycle();
if (lang != null) {
return new Locale(lang);
} else {
return null;
}
}
private static class ContextLocaleWrapper extends ContextThemeWrapper {
@Nullable
private Locale defaultLocale = null;
private ContextLocaleWrapper(Context context, Locale locale) {
this(context, locale, false);
}
private ContextLocaleWrapper(Context context, Locale locale, boolean overwriteDefaultLocale) {
super(context, context.getTheme());
Configuration configuration = new Configuration(context.getResources().getConfiguration());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(locale);
configuration.setLayoutDirection(locale);
} else {
configuration.locale = locale;
}
applyOverrideConfiguration(configuration);
// For prior to Android N, overwrite default Locale
if (overwriteDefaultLocale
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.N
&& !Locale.getDefault().equals(defaultLocale)) {
defaultLocale = Locale.getDefault();
Locale.setDefault(locale);
}
}
public void resetDefaultLocale() {
// For prior to Android N, reset the overwritten default Locale
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N && defaultLocale != null) {
Locale.setDefault(defaultLocale);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="LocaleTimePicker">
<attr format="string" name="locale"/>
</declare-styleable>
</resources>
<xxx.LocaleTimePicker
android:id="@+id/time_picker"
...
app:locale="ja"
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment