我有一个提供 4 种语言版本的应用程序,可以在应用程序内进行选择。在 Android 上,DatePicker 有一个标题。即使在设置了区域设置之后,该标题似乎也始终倾向于设备设置的区域设置。只有标题可以做到这一点,因为 DatePicker 的功能部分采用应用程序选择的语言。
以下是应用程序设置为韩语时的样子。
如何将 8 月 24 日星期四更改为韩语?我已将 Xamarin 和 Android 区域设置设置为韩语。日期选择器渲染器中是否有我可以设置的属性?
谢谢。
最佳答案
如果您正在执行类似的操作来应用新的区域设置上下文基本配置:
protected override void AttachBaseContext(Android.Content.Context @base)
{
Locale locale = Locale.Korean;
Locale.SetDefault(Locale.Category.Format, locale);
@base.Resources.Configuration.SetLocale(locale);
var newContext = @base.CreateConfigurationContext(@base.Resources.Configuration);
base.AttachBaseContext(newContext);
}
Material-design CalendarView
不正确地遵循传递给其 .ctor 的上下文的区域设置,最终会得到错误的标题本地化,如问题中所示;-(
一种选择是子类化 DatePicker
并重新实现 DatePickerCalendarDelegate
并将其应用到子类 AlertDialog
,但这有点为了正确解决问题而编写了大量的代码。
所以这是我一直在使用的一个修复(黑客)(针对 SO 进行了简化,因此您需要 API 进行各种 API 级别检查等......):
Material 设计修复(包括 Oreo beta):
// globals/cached
bool headerChangeFlag = true;
TextView headerTextView;
string headerDatePatternLocale;
SimpleDateFormat monthDayFormatLocale;
void SetHeaderMonthDay(DatePickerDialog dialog, Locale locale)
{
if (headerTextView == null)
{
// Material Design formatted CalendarView being used, need to do API level check and skip on older APIs
var id = base.Resources.GetIdentifier("date_picker_header_date", "id", "android");
headerTextView = dialog.DatePicker.FindViewById<TextView>(id);
headerDatePatternLocale = Android.Text.Format.DateFormat.GetBestDateTimePattern(locale, "EMMMd");
monthDayFormatLocale = new SimpleDateFormat(headerDatePatternLocale, locale);
headerTextView.SetTextColor(Android.Graphics.Color.Red);
headerTextView.TextChanged += (sender, e) =>
{
headerChangeFlag = !headerChangeFlag;
if (!headerChangeFlag)
return;
SetHeaderMonthDay(dialog, locale);
};
}
var selectedDateLocale = monthDayFormatLocale.Format(new Date((long)dialog.DatePicker.DateTime.ToUniversalTime().Subtract(
new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc)).TotalMilliseconds));
headerTextView.Text = selectedDateLocale;
}
用法:
var dialog = new DatePickerDialog(this);
dialog.Show();
SetHeaderMonthDay(dialog, Locale.Korean); // Call once, the text change event will update it when user changes date...
结果:
关于android - 设置Android DatePicker标题语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871800/