如何在Android DatePicker中设置自定义月份的名称?

时间:2015-06-17 13:16:06

标签: android datepicker

如何在Android DatePicker中设置自定义月份名称? 例如:new String [] {“January”,“February”,...}。

1 个答案:

答案 0 :(得分:1)

您可以创建一个自定义DatePicker,扩展系统类DatePicker,如下所示:

class MyCustomDatePicker extends DatePicker {
    public MyCustomDatePicker(Context context, AttributeSet attrs) {
         super(context, attrs);
         Field[] fields = DatePicker.class.getDeclaredFields();
         try {
             String[] s = new String[] {"January","February","March","April","May","June","July","August","September","October","November","December"};
             for (Field field : fields) {
                 field.setAccessible(true);
                 if (TextUtils.equals(field.getName(), "mMonthSpinner")) {
                      NumberPicker monthPicker = (NumberPicker) field.get(this);
                      monthPicker.setMinValue(0);
                      monthPicker.setMaxValue(11);
                      monthPicker.setDisplayedValues(s);
                 } 
                 if (TextUtils.equals(field.getName(), "mShortMonths")) {
                      field.set(this, s);
                 }
              }
       }
       catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
       }
    }
}

然后你需要在xml布局中将DatePicker声明为自定义datePicker,例如:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >

    <com.your.project.package.MyCustomDatePicker
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/myDatePicker" />
</LinearLayout>