kotlin Android Studio在日期选择器中仅列出可选择的日期

0lvr5msh  于 6个月前  发布在  Kotlin
关注(0)|答案(1)|浏览(113)

标题,我想有一个列表(数组,XML,文本,无论是最简单的),我想只有这些日期(有日期的差距)在日期选择器是可选的。我知道如何设置最小和最大日期,但没有某些日期。
代码到目前为止

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
}

字符串
如果有一个dialog.dataPicker.addDate或类似的东西,我可以为它计算出for循环,但任何指针都会有所帮助,谢谢。

vq8itlhq

vq8itlhq1#

解决方案是为datepicker对话框创建自己的类,您可以扩展DatePickerDialog并在那里实现自己的逻辑来处理某些日期更改事件:

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)
        }
    }
}

字符串
希望这对你有帮助。

相关问题