Android API 19设置hy locale时AM/PM显示过长异常求助
Android API 19 亚美尼亚语区域12小时制时间过长适配方案
问题核心
Android API 19 中,当区域设置为亚美尼亚语(hy)时,12小时制下的上午/下午标识默认显示为长字符串 կեսօրից առաջ,导致UI适配问题;而标准Java环境中相同代码会显示短标识(如AM),这是因为Android与标准Java的区域设置数据实现不同。
以下是针对TextClock组件和自定义时间格式化的解决方案:
一、适配TextClock组件
TextClock默认依赖系统区域设置格式,API 19无法直接修改其内置的AM/PM字符串,可通过两种方式解决:
1. 自定义格式并手动判断上下午
直接指定TextClock的12小时制格式,结合Calendar判断当前时段,替换为短标识:
TextClock textClock = findViewById(R.id.your_text_clock); Calendar calendar = Calendar.getInstance(); // 判断是否为上午 boolean isAm = calendar.get(Calendar.AM_PM) == Calendar.AM; // 设置自定义12小时制格式,使用亚美尼亚语短标识或英文AM/PM textClock.setFormat12Hour(String.format("h:mm %s", isAm ? "ԿԱ" : "ԿՁ")); // 若需要固定显示英文:textClock.setFormat12Hour("h:mm " + (isAm ? "AM" : "PM"));
2. 替换为TextView手动更新时间
若需要更灵活的格式控制,可改用TextView结合自定义SimpleDateFormat定时更新:
TextView timeTextView = findViewById(R.id.time_text_view); Locale hyLocale = new Locale("hy"); // 自定义DateFormatSymbols,替换AM/PM为短字符串 DateFormatSymbols symbols = new DateFormatSymbols(hyLocale); symbols.setAmPmStrings(new String[]{"ԿԱ", "ԿՁ"}); SimpleDateFormat customTimeFormat = new SimpleDateFormat("h:mm aa", symbols); // 每秒更新时间 new Timer().scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(() -> { timeTextView.setText(customTimeFormat.format(new Date())); }); } }, 0, 1000);
二、自定义SimpleDateFormat的解决方案
你之前尝试修改DateFormatSymbols但未正确应用,只需将修改后的symbols传入SimpleDateFormat构造方法即可:
Locale hyLocale = new Locale("hy"); DateFormatSymbols sym = new DateFormatSymbols(hyLocale); // 设置自定义AM/PM字符串,可选择亚美尼亚语短标识或英文 sym.setAmPmStrings(new String[]{"ԿԱ", "ԿՁ"}); // 将sym传入SimpleDateFormat DateFormat timeOnly = new SimpleDateFormat("h:mm aa", sym); Date fullDate = new Date(); String callTime = timeOnly.format(fullDate);
内容的提问来源于stack exchange,提问作者Matevž Jecl
相关产品推荐
相关产品推荐

