【发布时间】:2021-08-11 15:01:31
【问题描述】:
我正在尝试通过对开始和结束时间使用单独的日期和时间选择器来设置事件的日期和时间。
开始日期和开始时间 结束日期和结束时间
我整理的代码更新了日期,但时间没有改变
任何人都可以就这个问题提供指导吗?
谢谢
代码如下:
private val START_CAL_ID = 456
private lateinit var endCalendar: Calendar
private val END_CAL_ID = 678
private lateinit var endTimeCalendar: Calendar
private val calendar = Calendar.getInstance()
点击日期显示日期选择器,点击时间显示时间选择器
private fun showCalendar(calendarId: Int) {
val datePicker = DatePickerDialog(
this,
R.style.DateTimePickerTheme,
{ datePicker: DatePicker, year: Int, month: Int, day: Int ->
if (calendarId == START_CAL_ID) {
startCalendar.set(year, month, day)
} else if (calendarId == END_CAL_ID) {
endCalendar.set(year, month, day)
}
updateDateFields()
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
)
datePicker.show()
}
private fun showTime(calendarId: Int) {
val timePickerDialog = TimePickerDialog(
this, R.style.DateTimePickerTheme,
{ view: TimePicker?, hourOfDay: Int, minute: Int ->
if (calendarId == START_CAL_ID) {
startCalendar.set(hourOfDay, minute)
} else if (calendarId == END_CAL_ID) {
endCalendar.set(hourOfDay, minute)
}
updateTimeFields()
},
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
false
)
timePickerDialog.show()
}
更新应用中的字段以正确格式显示所选数据
private fun updateDateFields() {
val formatter = SimpleDateFormat("MMM dd, yyyy", Locale.getDefault())
findViewById<TextView>(R.id.editEventStartDate).text = formatter.format(startCalendar.time)
findViewById<TextView>(R.id.editEventEndDate).text = formatter.format(endCalendar.time)
}
private fun updateTimeFields() {
val timeFormatter = SimpleDateFormat("hh.mm a", Locale.getDefault())
findViewById<TextView>(R.id.editEventStartTime).text =
timeFormatter.format(startCalendar.time)
findViewById<TextView>(R.id.editEventEndTime).text = timeFormatter.format(endCalendar.time)
}
【问题讨论】:
标签: android kotlin datepicker calendar timepicker