Search code examples
javaandroidtimekotlintimepicker

Select blocks of time with MaterialDateTimePicker


I want to show a clock where only a selected blocks of times can be selected. For example: I want the clock to only let me select times from 09:00 to 10:00 or from 12:00 to 12:30 or from 14:00 to 18:00. All hours outside those ranges should not me selectable.

Using MaterialDateTimePicker I was able to set a array of selected times:

val time = TimePickerDialog.newInstance(timeSet, true)
time.setSelectableTimes(arrayOf(Timepoint(10), Timepoint(11)))

But this only let me select the time of 10:00 and 11:00 and not the interval between them.

Is it possible to do a behaviour like I explained with this library?


Solution

  • So I decided to create a new method to create an array of TimePoints:

    private fun getTimes(array: JSONArray): Array<Timepoint> {
        val times = arrayListOf<Timepoint>()
        for (i in 0..array.length().minus(1)) {
            val format = SimpleDateFormat("HH:mm", Locale.getDefault())
    
            val start = Calendar.getInstance()
            start.time = format.parse(array.getJSONObject(i).getString("start"))
    
            val end = Calendar.getInstance()
            end.time = format.parse(array.getJSONObject(i).getString("end"))
    
            while (!start.after(end)) {
                times.add(Timepoint(start.get(Calendar.HOUR_OF_DAY), start.get(Calendar.MINUTE)))
                start.add(Calendar.MINUTE, 1)
            }
        }
    
        return times.toArray(arrayOfNulls<Timepoint>(times.size))
    }
    

    And I would call him like that:

    time.setSelectableTimes(getTimes(array))
    

    Explanation:

    By using the method:

    time.setSelectableTimes(arrayOf(Timepoint(10), Timepoint(11)))
    

    I would only be enable to choose the times of 10:00h and 11:00h respectively, so the solution is to find all the times between 10:00h and 11:00h and add them to an array. Only then with this new array I can call the method above.