如何使用 Kotlin 在片段中设置日期选择器?

how to set date picker in fragment using Kotlin?

我想使用这个库显示日期选择器对话框 https://github.com/wdullaer/MaterialDateTimePicker

implementation "com.wdullaer:materialdatetimepicker:3.6.4"

这是我片段中的代码

import com.wdullaer.materialdatetimepicker.date.DatePickerDialog

        val now = Calendar.getInstance()
        val currentYear: Int = now.get(Calendar.YEAR)
        val currentMonth: Int = now.get(Calendar.MONTH)
        val currentDay: Int = now.get(Calendar.DAY_OF_MONTH)

        val datePickerDialog = DatePickerDialog.newInstance(DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->

            // do something here


        }, currentYear, currentMonth, currentDay)

        datePickerDialog.setTitle("INI JUDUL")
        datePickerDialog.setAccentColor(resources.getColor(R.color.colorPrimary))
        datePickerDialog.setOkText("SIP")
        datePickerDialog.setCancelText("GA JADI")
        datePickerDialog.show(fragmentManager,"")

但是当我想在这一行 datePickerDialog.show(fragmentManager,"") 中显示日期选择器对话框时出现错误,就像这样

我相信我已经提供了正确的参数,但仍然......它给出了一个错误

这是片段管理器类型:

但是如果我强制这样解包,它仍然会报错

我不知道这是不是完美的方法我已经尝试过这段代码并且它可以工作,但该方法已被弃用。如果您找到其他方法,请告诉我。

val now = Calendar.getInstance()
        val currentYear: Int = now.get(Calendar.YEAR)
        val currentMonth: Int = now.get(Calendar.MONTH)
        val currentDay: Int = now.get(Calendar.DAY_OF_MONTH)

        val datePickerDialog = DatePickerDialog.newInstance(DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->

            // do something here


        }, currentYear, currentMonth, currentDay)

        datePickerDialog.setTitle("INI JUDUL")
        datePickerDialog.setAccentColor(resources.getColor(R.color.colorPrimary))
        datePickerDialog.setOkText("SIP")
        datePickerDialog.setCancelText("GA JADI")
        datePickerDialog.show(activity!!.fragmentManager, "Datepickerdialog"); 

希望有用!

刚试过这个,效果很好:

    val now = Calendar.getInstance()
    val currentYear: Int = now.get(Calendar.YEAR)
    val currentMonth: Int = now.get(Calendar.MONTH)
    val currentDay: Int = now.get(Calendar.DAY_OF_MONTH)

    val datePickerDialog = DatePickerDialog.newInstance(DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->

        // do something here


    }, currentYear, currentMonth, currentDay)

    datePickerDialog.setTitle("INI JUDUL")
    datePickerDialog.setAccentColor(resources.getColor(R.color.colorPrimary))
    datePickerDialog.setOkText("SIP")
    datePickerDialog.setCancelText("GA JADI")
    datePickerDialog.show(parentFragmentManager,"")

尝试清理项目并使缓存失效。它可能会有所帮助。

使用 androidX,您应该使用最新版本:

implementation 'com.wdullaer:materialdatetimepicker:4.2.3'

在片段中:

fragmentManager?.let { manager ->
            datePickerDialog.show(manager, "DatePickerDialog")
        }