TimePicker AM/PM 不随语言环境改变

TimePicker AM/PM not changing with locale

对于阿拉伯语,我想以英语格式显示 TimePicker。

Locale.setDefault(Locale.ENGLISH); 为我工作但 AM/PM 没有改变.

我创建了一个函数来设置AM/PM使用反射,你可以参考:

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class CustomTimePicker {
    static void initPicker(Object object, String[] values) {
        try {
            Field[] fields = object.getClass().getDeclaredFields();

            for (Field field : fields) {
                // If there's a delegate, we use it instead.
                if (field.getName().equals("mDelegate")) {
                    field.setAccessible(true);
                    object = field.get(object);
                    fields = object.getClass().getDeclaredFields();
                    break;
                }
            }

            for (Field field : fields) {
                if (field.getName().equals("mAmPmStrings") ||
                        field.getName().equals("mShortMonths")) {
                    field.setAccessible(true);
                    field.set(object, values);
                } else if (field.getName().equals("mAmPmSpinner") ||
                        field.getName().equals("mMonthSpinner")) {
                    field.setAccessible(true);
                    Object innerObject = field.get(object);
                    Method method = innerObject.getClass().getDeclaredMethod(
                            "setDisplayedValues", String[].class);
                    method.setAccessible(true);
                    method.invoke(innerObject, (Object) values);
                }
            }

            Method[] methods = object.getClass().getDeclaredMethods();

            for (Method method : methods) {
                if (method.getName().equals("updateAmPmControl") ||
                        method.getName().equals("updateSpinners")) {
                    method.setAccessible(true);
                    method.invoke(object);
                    break;
                }
            }
        } catch (Exception e) {
            Log.e("error", e.getMessage(), e);
        }
    }
}

要使用,您需要设置默认语言并更改 AM/PM - 在 res/values/attrs.xml

中创建文件数组 am_pm
<string-array name="am_pm">
    <item>am</item>
    <item>pm</item>
</string-array>

- 使用时:

Locale.setDefault(Locale.ENGLISH)
CustomTimePicker.initPicker(yourTimePicker, resources.getStringArray(R.array.am_pm))

- 结果: