Android Date Time picker in one dialog

后端 未结 9 1193
抹茶落季
抹茶落季 2021-02-07 01:31

I am using material Date Time picker for my Android app. But I want to combine the Date and Time picker in one dialog.

<
9条回答
  •  孤独总比滥情好
    2021-02-07 02:00

    Kotlin

    Here's the tested Kotlin code for combining the DatePickerDialog and TimePickerDialog together. It becomes simpler because of the support of the closures in Kotlin. The following function should be placed in your Fragment or Activity. The requireContext() method is a member of Fragment. If you are using Activity, use applicationContext instead.

    private fun pickDateTime() {
        val currentDateTime = Calendar.getInstance()
        val startYear = currentDateTime.get(Calendar.YEAR)
        val startMonth = currentDateTime.get(Calendar.MONTH)
        val startDay = currentDateTime.get(Calendar.DAY_OF_MONTH)
        val startHour = currentDateTime.get(Calendar.HOUR_OF_DAY)
        val startMinute = currentDateTime.get(Calendar.MINUTE)
    
        DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { _, year, month, day ->
            TimePickerDialog(requireContext(), TimePickerDialog.OnTimeSetListener { _, hour, minute ->
                val pickedDateTime = Calendar.getInstance()
                pickedDateTime.set(year, month, day, hour, minute)
                doSomethingWith(pickedDateTime)
            }, startHour, startMinute, false).show()
        }, startYear, startMonth, startDay).show()
    }
    

    Call the above function in onClickListener of your button as following:

    button.setOnClickListener { pickDateTime() }
    

    That's it!

    If you want to show clock in 12 hour or 24 hour format depending on user's settings, replace false with DateFormat.is24HourFormat(requireContext())

提交回复
热议问题