OGeek|极客世界-中国程序员成长平台

标题: android - 从 Kotlin Android 中的 DatePickerDialog 获取日期 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-9 06:48
标题: android - 从 Kotlin Android 中的 DatePickerDialog 获取日期

在正确更新 statusDateID 的意义上,下面的代码 fragment “有效”。我遇到的问题是,虽然它正确设置了 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 都显示当前日期。



Best Answer-推荐答案


只需在 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()

关于android - 从 Kotlin Android 中的 DatePickerDialog 获取日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46588071/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) Powered by Discuz! X3.4