how to select year in datepickerdialog android?

Raj Lalwani picture Raj Lalwani · Sep 15, 2015 · Viewed 7.4k times · Source

I am new to Android programming. Please help.

I am using Fragment that creates Material design DatePickerDialog on click of EditText. Trouble is it is set to current date (set by me). But, if user has to select the date in the past ... say, 10 years ago, user has to scroll each month which is painful. e.g. shown below:

Is there a way to make your select the year? This way user can navigate to the year.

enter image description here

Answer

Juan Labrador picture Juan Labrador · Sep 15, 2015

I think than that is because you don't have a minimum date or maxim date. If you try to create a custom dialog with DatePicker, it works. I have a same example with an Edittext. I call this method when the user to click in Edittext.

private void showDateDialog() {
    mLayoutInflater = getLayoutInflater();
    mCustomDatePicker = mLayoutInflater.inflate(R.layout.custom_date_picker, null);

    mDatePicker = (DatePicker) mCustomDatePicker.findViewById(R.id.datePicker);
    mDatePicker.setMaxDate(Calendar.getInstance().getTime().getTime());

    mCalendar = Calendar.getInstance();

    mDialog = new AlertDialog.Builder(this);
    mDialog.setView(mCustomDatePicker);
    mDialog.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            mCalendar.set(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
            mBirthdayEdit.setText(mFormatDate.format(mCalendar.getTime()));

        }
    }).setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    mDialog.create();
    mDialog.show();
}

You layout

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <DatePicker
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/datePicker"
        android:layout_gravity="center_horizontal"
        android:spinnersShown="true"
        android:calendarViewShown="false"
        android:layout_alignParentTop="true"/>
</RelativeLayout>