从Kotlin Android中的DatePickerDialog获取日期

下面的代码片段“有效”,正确地更新了statusDateID。 我遇到的问题是,虽然它正确地设置statusDateID,日期将不会持续,当我更新mh.entryDate它始终是当前日期。

我如何获得对话外的日期。 这样我就可以用选择的日期更新mh.entryDate,而不是当前的日期。

感谢您的时间。

fun changeDate(view: View) { var date: Calendar = Calendar.getInstance() var thisAYear = date.get(Calendar.YEAR).toInt() var thisAMonth = date.get(Calendar.MONTH).toInt() var thisADay = date.get(Calendar.DAY_OF_MONTH).toInt() val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view2, thisYear, thisMonth, thisDay -> // Display Selected date in textbox thisAMonth = thisMonth + 1 thisADay = thisDay thisAYear = thisYear statusDateID.setText("Date: " + thisAMonth + "/" + thisDay + "/" + thisYear) val newDate:Calendar =Calendar.getInstance() newDate.set(thisYear, thisMonth, thisDay) }, thisAYear, thisAMonth, thisADay) dpd.show() mh.entryDate = date.timeInMillis println("DATE DATA: "+thisAYear+ " "+thisAMonth+" " + thisADay) println("DATE CHANGED MILLISECS = "+mh.entryDate) } 

mh.entryDate被定义为全局的,并且被定义为LONG。 通过调试println语句,DATE DATA和DATE CHANGED MILLISECS都显示当前日期。

只需在DatePickerDialog.OnDateSetListener方法中设置日期与mh.entryDate = newDate.timeInMillis

 val dpd = DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view2, thisYear, thisMonth, thisDay -> // Display Selected date in textbox thisAMonth = thisMonth + 1 thisADay = thisDay thisAYear = thisYear statusDateID.setText("Date: " + thisAMonth + "/" + thisDay + "/" + thisYear) val newDate:Calendar =Calendar.getInstance() newDate.set(thisYear, thisMonth, thisDay) mh.entryDate = newDate.timeInMillis // setting new date }, thisAYear, thisAMonth, thisADay) dpd.show() 

您正在将date对象实例化为日历中的新实例,但是您没有使用选择器中的日期进行更新。 date被创建,查询,但从未更新。