Android studio making only list of dates selectable in date picker

180 Views Asked by At

Title, I want to have a list (array, xml, text whatever is easiest) and I want to have only those dates(there are gaps in the dates) in the date picker be selectable. I know how to set the min and max date but nothing for certain dates.

my code so far

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

// Use the current date as the default date in the picker. val c = Calendar.getInstance() val year = c.get(Calendar.YEAR) val month = c.get(Calendar.MONTH) val day = c.get(Calendar.DAY_OF_MONTH)



val dialog = DatePickerDialog(requireContext(), this, year, month, day)

dialog.datePicker.maxDate = Date().time

return dialog
}

If there is a dialog.dataPicker.addDate or something similar I can work out the for loop for it but any pointers would help, Thanks.

1

There are 1 best solutions below

0
f4pl0 On

Solution would be to create your own class for the datepicker dialog, you can extend the DatePickerDialog and implement your own logic there for handling certain date change events:

    class CustomDatePickerDialog(
        // context, date set listener, and list of selectable dates
    ) : DatePickerDialog(context, null, 0, 0, 0) {

    override fun onDateChanged(view: DatePicker, year: Int, month: Int, day: Int) {
        // Here you check if the selected date is in your list
        val selectedDate = Calendar.getInstance()
        selectedDate.set(year, month, day)
        val selectedTimeInMillis = selectedDate.timeInMillis
        
        // If it is, call the super.onDateChanged
        if (selectableDates.contains(selectedTimeInMillis)) {
            super.onDateChanged(view, year, month, day)
        }
    }
}

Hope this helps.