Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

datepicker - Custom Date Picker Dialog in Android Lollipop

I want a date picker to show only Month and Year. I've customized the Date Picker to do so i.e., to remove 'day' field from the picker,but in Android Lollipop Am getting picker with Day, Month and Year. Following is my piece of code. Please help me to know the problem. Thanks in advance.

    try {
        Field f[] = mDatePicker.getClass().getDeclaredFields();
        for (Field field : f) {

            if (field.getName().equals("mDaySpinner") || field.getName().equals("mDayPicker")) {
                field.setAccessible(true);
                Object dayPicker = new Object();
                dayPicker = field.get(mDatePicker);
                ((View) dayPicker).setVisibility(View.GONE);
            }

        }
    } catch (SecurityException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using reflection to find and hide UI elements is not really a great practice. In your case, it stopped working in lollipop because the mDaySpinner is now contained in an internal private static DatePickerSpinngerDelegate class within the DatePicker class.

I would recommend going through the view hierarchy to find and hide the day spinner element instead. I wrote the following code that works in lollipop:

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    int daySpinnerId = Resources.getSystem().getIdentifier("day", "id", "android");
    if (daySpinnerId != 0) {
        View daySpinner = datePicker.findViewById(daySpinnerId);
        if (daySpinner != null) {
            daySpinner.setVisibility(View.GONE);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...