Hide Year field in Android DatePicker?

A super easy way that I found to implement a DatePicker is to call it in xml:

    <DatePicker
    android:id="@+id/thePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

and then hide whichever field you want (in this case the year) in java:

    picker = (DatePicker) findViewById(R.id.thePicker);
    try {
        Field f[] = picker.getClass().getDeclaredFields();
        for (Field field : f) {
            if (field.getName().equals("mYearPicker")) {
                field.setAccessible(true);
                Object yearPicker = new Object();
                yearPicker = field.get(picker);
                ((View) yearPicker).setVisibility(View.GONE);
            }
        }
    } 
    catch (SecurityException e) {
        Log.d("ERROR", e.getMessage());
    } 
    catch (IllegalArgumentException e) {
        Log.d("ERROR", e.getMessage());
    } 
    catch (IllegalAccessException e) {
        Log.d("ERROR", e.getMessage());
    }

Leave a Comment