首页 文章

更改语言环境时更新Textclock

提问于
浏览
0

我在我的应用布局中使用了一个textClock小部件 . 我必须支持不同的语言,并添加dateformat必须是完整的日期,如“EEEE,dd MMMM yyyy HH:mm:ss a” . 问题是,days name和Months始终使用默认语言环境 . 当我以编程方式更改区域设置时,它不会更改 .

有什么建议吗?这不应该自动处理吗?

2 回答

  • 1

    使用public void setTextLocale (Locale locale)尝试此操作:

    Resources res = context.getResources();
    // Change locale settings in the app.
    DisplayMetrics dm = res.getDisplayMetrics();
    android.content.res.Configuration conf = res.getConfiguration();
    conf.locale = new Locale(language_code.toLowerCase());
    yourTextClock.setTextLocale(conf.locale);
    res.updateConfiguration(conf, dm);
    
  • 1

    它无法使用默认小部件 . 所以我使用了我自己的类,并按预期工作 . 您只需确保以正确的方式更改您的区域设置 .

    public class MyTextClock extends android.widget.TextClock {
    
    
        public MyTextClock(Context context) {
            super(context);
            setLocaleDateFormat();
        }
    
        public MyTextClock(Context context, AttributeSet attrs) {
            super(context, attrs);
            setLocaleDateFormat();
        }
    
        public MyTextClock(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            setLocaleDateFormat();
        }
    
        private void setLocaleDateFormat()
        {
            Locale currentLocale = getResources().getConfiguration().locale;
            Calendar cal = GregorianCalendar.getInstance(TimeZone.getDefault(), currentLocale);
    
            String dayName = cal.getDisplayName(cal.DAY_OF_WEEK, Calendar.LONG, currentLocale);
            String monthName =cal.getDisplayName(cal.MONTH, Calendar.LONG, currentLocale);
    
            this.setFormat12Hour("'"+dayName+"' '"+monthName+"' dd, yyyy h:m:ss a");
            this.setFormat24Hour("'"+dayName+"', dd '"+monthName+"' yyyy HH:mm:ss");
        }
    }
    

相关问题