How to set custom months' names in Android DatePicker?

前端 未结 1 1523
花落未央
花落未央 2021-01-15 06:35

How can I set custom months\' names in Android DatePicker? For example: new String[]{\"January\", \"February\", ... }.

相关标签:
1条回答
  • 2021-01-15 06:57

    You could create a custom DatePicker that extends the system class DatePicker like this:

    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();
           }
        }
    }
    

    And then you need to declare the DatePicker as your custom datePicker in the xml layout like this for example:

    <?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>
    
    0 讨论(0)
提交回复
热议问题