Show date picker with month and year only for lollipop 5.0 in android

Garima Mathur picture Garima Mathur · May 11, 2015 · Viewed 12.1k times · Source

Show date picker with month and year only for lollipop 5.0 in android, it can be done in lower versions but how can i do it for android 5.0.

Answer

Christian Abella picture Christian Abella · May 12, 2015

This can be done by setting your DatePicker to spinner mode and getting the Spinner for Day and hiding it programmatically.

Here is the XML (dialog_date_picker.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:padding="8dp"
    android:layout_height="match_parent">

    <DatePicker
        android:id="@+id/date_picker"
        android:layout_width="match_parent"
        android:calendarViewShown="false"
        android:datePickerMode="spinner"
        android:layout_weight="4"
        android:layout_height="0dp"
        />

    <Button
        android:id="@+id/date_time_set"
        android:layout_weight="1"
        android:layout_width="match_parent"
        android:text="Set"
        android:layout_height="0dp" />

</LinearLayout>

Here is the code to do it.

private Calendar mCalendar;
...

mCalendar = Calendar.getInstance();

final View dialogView = View.inflate(this, R.layout.dialog_date_picker, null);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();

DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);

datePicker.init(mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DAY_OF_MONTH),null);


LinearLayout ll = (LinearLayout)datePicker.getChildAt(0);
LinearLayout ll2 = (LinearLayout)ll.getChildAt(0);
ll2.getChildAt(0).setVisibility(View.INVISIBLE);

dialogView.findViewById(R.id.date_time_set).setOnClickListener(new View.OnClickListener()
{
  @Override
  public void onClick(View view)
  {    
    DatePicker datePicker = (DatePicker) dialogView.findViewById(R.id.date_picker);

    mCalendar = new GregorianCalendar(datePicker.getYear(),
    datePicker.getMonth(),
    datePicker.getDayOfMonth());

    alertDialog.dismiss();
    }
});