drac94 drac94 - 3 months ago 17
Android Question

Hide Calenderview from DatePicker programatically in API 21

I'm having the same issue as this thread: Android Material Design Inline Datepicker issue, but I am not using an XML layout, instead I'm building the DatePicker programatically.

This is the code I am using but is not working

DatePicker dpView = new DatePicker(ctx);
dpView.setCalendarViewShown(false);
dpView.setSpinnersShown(true);


how can I make it work?

Thanks

Answer

The problem in Android 5.0 is the "mode" which determines whether to use a calendar or not is read at construct time, and in code you can't set the mode until after it has been constructed, thus it's too late. (Source is here: DatePicker Source Code)

My solution was to create my own reusable DatePicker layout that specifies the "no calendar" mode, and construct my DateTimes programmatically with that layout instead of Android's default.

Bottom line is, create a "DatePicker.axml" file, put it in the resources folder, and paste the following as its contents:

<?xml version="1.0" encoding="utf-8"?>

<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:calendarViewShown="false"
          android:datePickerMode="spinner"/>

and declare it wherever you need in code like this:

LayoutInflater inflater = LayoutInflater.From( Activity );
DatePicker datePicker = (DatePicker)inflater.Inflate( Resource.Layout.DatePicker, null );