Ayush
Ayush

Reputation: 23

android material date picker is very slow

I am using material date picker in my app to pick two dates but when try to call this it open in many seconds also when try to select date they are also laggy and takes time.


fun showDatePicker(activity: Activity, fragmentManager: FragmentManager, onDateSelected: (startDate: String, endDate: String) -> Unit) {

    val constraintsBuilder = CalendarConstraints.Builder()
    val calendar = Calendar.getInstance()
    calendar.add(Calendar.YEAR, -1) // 1 yr ago
    val minDate = calendar.timeInMillis
    constraintsBuilder.setStart(minDate)

    calendar.add(Calendar.YEAR, 2) // max yr 2 years from now
    val maxDate = calendar.timeInMillis
    constraintsBuilder.setEnd(maxDate)

    val dateRange =
        MaterialDatePicker.Builder.dateRangePicker()
            .setTitleText("Select dates")
            .setSelection(Pair(null, null))
            .setCalendarConstraints(constraintsBuilder.build()) // Apply the constraints
            .build()

    val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy", Locale.getDefault())

    dateRange.show(fragmentManager, "DATE_RANGE_PICKER")

    dateRange.addOnPositiveButtonClickListener { selection ->
        val startDate = simpleDateFormat.format(selection.first)
        val endDate = simpleDateFormat.format(selection.second)
Log.e("date--->>>>","not-formatted $selection.first")
        Log.e("date--->>>>","formatted $startDate")
        onDateSelected(startDate, endDate)
    }
}


i call it in my fragment oncreate view

 binding.calendar.setOnClickListener {

            showDatePicker(requireActivity(), requireActivity().supportFragmentManager) { startDate, endDate ->
                binding.selectedDate.text = "$startDate - $endDate"
                val firstDate=startDate
                val lastDate=endDate
            }
        }

please guide if there is something i am missing or add to make it smooth . Thanks in advance :)

Upvotes: 0

Views: 225

Answers (0)

Related Questions