我试图在单击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是我的edittext,我在其中设置并设置用户年龄但是每次我选择一个值时,我都会得到当前日期。
您必须将日历设置为日期设置
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())
}