I need to set a datePickerDialog
, and disable all future dates and all dates before one month ago,
for example: If today is 04/05/2020 I need the range from 04/04/2020 - 04/05/2020.
How can I set it? I tried the min/max approach but the problem is that I uses different fragment that extended DialogFragment
.
This is my code:
class DatePickerFragmentDialog : DialogFragment(), DatePickerDialog.OnDateSetListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
// Use the current date as the default date in the picker
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
// Create a new instance of DatePickerDialog and return it
return DatePickerDialog(requireActivity(), this, year, month, day)
}
override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) {
}
}
And I call it from my main fragment here:
DatePickerFragmentDialog().show(parentFragmentManager, "datePicker" )
Also - since getSupportFragment was deprecated I call here parentFragmentManager
, this is the right choice?
And final question - I can get the user pick from onDateSet
function, but the problem is that this function is in DatePickerFragmentDialog
how can I pass the variables from this function to my main fragment and views?
For your first question, you can set min date and max date inside onCreateDialog
:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val d = DatePickerDialog(requireActivity(), this , year, month, day)
val dp = d.datePicker
dp.maxDate = //Do your calculation
dp.min= //Do your calculation
return d
}
And for your other question - you can implement the DatePickerDialog.OnDateSetListener
inside your main fragment and call onDateSet
from there