Android端DatePicker与TimePicker强制显示英文(阿拉伯语RTL环境)
解决DatePicker/TimePicker在阿拉伯语系统下强制显示英文的问题


问题描述
我已将设备语言设置为阿拉伯语以实现RTL布局,但现在需要让DatePicker和TimePicker强制显示为英文。
解决方案
方法1:初始化Picker时直接指定英文Locale
在创建DatePickerDialog或TimePickerDialog时,给Picker组件设置英文Locale:
// DatePickerDialog示例 DatePickerDialog datePickerDialog = new DatePickerDialog( this, android.R.style.Theme_Holo_Light_Dialog_MinWidth, yourDateSetListener, currentYear, currentMonth, currentDay ); datePickerDialog.getDatePicker().setLocale(Locale.ENGLISH); datePickerDialog.show(); // TimePickerDialog示例 TimePickerDialog timePickerDialog = new TimePickerDialog( this, yourTimeSetListener, currentHour, currentMinute, true ); timePickerDialog.getPicker().setLocale(Locale.ENGLISH); timePickerDialog.show();
方法2:用ContextWrapper包装英文Locale
如果需要让多个Picker统一生效,可以自定义ContextWrapper来强制使用英文Locale,再用这个包装后的Context创建Picker:
public class EnglishContextWrapper extends ContextWrapper { public EnglishContextWrapper(Context base) { super(base); } public static ContextWrapper wrap(Context context) { Configuration config = context.getResources().getConfiguration(); config.setLocale(Locale.ENGLISH); // 适配Android 7.0及以上版本 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { context = context.createConfigurationContext(config); } else { context.getResources().updateConfiguration(config, context.getResources().getDisplayMetrics()); } return new EnglishContextWrapper(context); } }
使用示例:
DatePickerDialog datePickerDialog = new DatePickerDialog( EnglishContextWrapper.wrap(this), yourDateSetListener, currentYear, currentMonth, currentDay ); datePickerDialog.show();
方法3:XML布局中直接指定Locale
如果是在XML布局里使用DatePicker或TimePicker组件,可直接添加android:locale="en"属性:
<DatePicker android:id="@+id/datePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:locale="en"/> <TimePicker android:id="@+id/timePicker" android:layout_width="wrap_content" android:layout_height="wrap_content" android:locale="en"/>
内容的提问来源于stack exchange,提问作者bala
相关产品推荐
相关产品推荐

