Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide Year field in Android DatePicker?

I'm using a basic DatePicker and I'm trying to figure out how to hide the Year field on the DatePickerDialog so that only the Month and Day are visible. I don't mind that the underlying code for the year would still be there, I'd just like to hide the Year Field in the Dialog. You know with something like:

((View) myYear).setVisibility(View.GONE);

which I know doesn't work because myYear is a int not a View, but something along those lines. Is it possible?

like image 299
kirktoon1882 Avatar asked May 01 '12 17:05

kirktoon1882


1 Answers

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());
    }
like image 76
kirktoon1882 Avatar answered Oct 20 '22 13:10

kirktoon1882