4

I'm implementing the DatePicker to prompt the user to select the date. I would like to change the default behavior of the DatePicker dialog so that it lets the user to first select the year.

  1. I already know that by clicking on the year, a new menu opens that allows the user to select the year. I would like it to open automatically first.

  2. I did research this and found this answer: how to select year in datepickerdialog android? In this post it is explained how to create a custom date picker in which you would be able to set the maximum date. However, it doesn't help with opening the year selection menu first.

Is it possible to achieve?

In case someone's interested, the translated code in Kotlin of creating a custom date picker dialog:

        val mCustomDatePicker = layoutInflater.inflate(com.example.meet.R.layout.custom_date_picker, null)

        var mDatePicker = mCustomDatePicker.findViewById(com.example.meet.R.id.mDatePicker) as DatePicker
        mDatePicker.maxDate = (Calendar.getInstance().getTime().getTime())

        val mDialog = AlertDialog.Builder(this)
        mDialog.setView(mCustomDatePicker)

        mDialog.setPositiveButton("OK", object : DialogInterface.OnClickListener {
            override fun onClick( dialog: DialogInterface, which: Int) {
//                mCalendar.set(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth());
//                mBirthdayEdit.setText(mFormatDate.format(mCalendar.getTime()));

            }
        }).setNegativeButton("Cancel", object: DialogInterface.OnClickListener {
            @Override
            override fun onClick( dialog: DialogInterface, which: Int) {
                dialog.dismiss()
            }
        })
        mDialog.create()
        mDialog.show()

enter image description here

sir-haver
  • 3,096
  • 7
  • 41
  • 85

1 Answers1

4

Try to use below code to achieve this:

DatePickerDialog dialog = new DatePickerDialog(
        context, // activity context
        listener, //date set listener
        year, 
        month, 
        day);

dialog.getDatePicker().getTouchables().get(0).performClick();

dialog.show();
Md. Asaduzzaman
  • 14,963
  • 2
  • 34
  • 46
  • I'm using the AlertDialog builder to implement the DatePicker, and this dialog doesn't take those methods such as getDatePicker. Is it possible to achieve with using that builder? I want to keep the prevention of the user from selecting future dates as well – sir-haver Jan 05 '20 at 17:30
  • Oh you're right I just need to set it like so in my case: mCustomDatePicker.datePickerLayout.touchables.get(0).performClick() – sir-haver Jan 05 '20 at 17:34