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

时间:2019-12-19 07:01:07

标签: android kotlin android-datepicker

我想使用此库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,"")中显示日期选择器对话框时出现错误,

enter image description here

我相信我提供了正确的论点,但是....它仍然给出错误

这是片段管理器类型: enter image description here

但是如果我强制这样展开,它仍然会出错 enter image description here

3 个答案:

答案 0 :(得分:1)

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

implementation 'com.wdullaer:materialdatetimepicker:4.2.3'

然后是片段:

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

答案 1 :(得分:0)

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

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"); 

希望它能工作!

答案 2 :(得分:0)

只需尝试一下,它就可以完美运行:

    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,"")

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