Edittext 仅显示当前日期,同时选择其他日期

Edittext is showing only current date, while selecting other dates

我试图在点击 editext 后打开一个日期选择器,我已经实现了,但是我面临一个问题,即每次我选择日期时 settext() 都只获取当前日期。不是以前的日期。

我已经实现了打开日期选择器。 也是我需要的格式。 成功通过18岁以上的检查

etDob.setOnClickListener {
    val calendar = Calendar.getInstance()
    val year = calendar.get(Calendar.YEAR)
    val month = calendar.get(Calendar.MONTH)
    val day = calendar.get(Calendar.DAY_OF_MONTH)


    val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
        val myFormat: String = "MM/dd/yyyy"

        val sdf = SimpleDateFormat(myFormat, Locale.US)
        val dob = sdf.format(calendar.getTime())
        etDob!!.setText(dob)

        val userAge = GregorianCalendar(year, month, day)

        val minAdultAge = GregorianCalendar()
        minAdultAge.add(Calendar.YEAR, -18)
        if (minAdultAge.before(userAge)) {
            Toast.makeText(this, "18 year", Toast.LENGTH_SHORT).show()
        }
    }, year, month, day)
    dpd.datePicker.maxDate = Calendar.getInstance().timeInMillis
    dpd.show()

etDob 是我打开并设置用户年龄的编辑文本 但每次我选择一个值时,我都会得到当前日期。

您必须在 Date Set 上设置日历

calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, monthOfYear)
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)

所以你的代码应该像-

val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->

calendar.set(Calendar.YEAR, year)
calendar.set(Calendar.MONTH, monthOfYear)
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
val myFormat: String = "MM/dd/yyyy"

val sdf = SimpleDateFormat(myFormat, Locale.US)
val dob = sdf.format(calendar.getTime())
}