如何在 Kotlin 的 DatePicker 中禁用未来日期 Android

How to disable Future date in DatePicker in Kotlin Android

我在使用 Kotlin 的 Android 项目中使用 DatePickerDialog。我已经成功创建了 DatePickerDialog 并且工作正常。 现在我想像在 DatePickerDialog 中一样进行一些验证,我想禁用未来的日期。 例如,今天日期是 2019 年 8 月 22 日我想禁用今天日期之后的所有日期。

我尝试使用 dateSetListener.getDatePicker().setMaxDate(System.currentTimeMillis())

但它不起作用

var cal = Calendar.getInstance()

      // create an OnDateSetListener

        val dateSetListener = object : DatePickerDialog.OnDateSetListener {

        override fun onDateSet(
            view: DatePicker, year: Int, monthOfYear: Int,
            dayOfMonth: Int
        ) {
            cal.set(Calendar.YEAR, year)
            cal.set(Calendar.MONTH, monthOfYear)
            cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
            updateDateInView()

        }

       // dateSetListener.getDatePicker().setMaxDate(calendar.getTimeInMillis());
    }

    // when you click on the button, show DatePickerDialog that is set with OnDateSetListener
    button_date!!.setOnClickListener(object : View.OnClickListener {
        override fun onClick(view: View) {

            DatePickerDialog(this@MainActivity,
                dateSetListener,
                // set DatePickerDialog to point to today's date when it loads up
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH)).show()
            }
    })```

试试这个

var dialog = DatePickerDialog(
                this@MainActivity,dateSetListener,
                // set DatePickerDialog to point to today's date when it loads up
                cal.get(Calendar.YEAR),
                cal.get(Calendar.MONTH),
                cal.get(Calendar.DAY_OF_MONTH)
            )

            dialog.datePicker.maxDate = Calendar.getInstance().timeInMillis
            dialog.show()