'Can't select date with datepickerdialog
I have some trouble using the DataPickerDialog in kotlin...
This is how I would like it to work:
First, when the user selects a date, it must update a textview and the dialog must close
But for now, when the user selects a date, nothing happens (apart from the update in the dialog itself).
Here is my code :
@AndroidEntryPoint
class AppointmentListFragment : Fragment() {
private var _binding: FragmentAppointmentListBinding? = null
private val binding: FragmentAppointmentListBinding
get() = _binding!!
private val viewModel: AppointmentMainViewModel by viewModels()
private val today = Calendar.getInstance()
private val day = today.get(Calendar.DAY_OF_MONTH)
private val month = today.get(Calendar.MONTH) + 1
private val year = today.get(Calendar.YEAR)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentAppointmentListBinding.inflate(inflater)
setDateText(
getString(
R.string.date_placeholder,
String.format("%02d", day),
String.format("%02d", month),
year
)
)
binding.appointmentDateButton.setOnClickListener {
val dpd = DatePickerDialog(
it.context,
{ datePicker, y, m, d ->
datePicker.minDate = System.currentTimeMillis()
setDateText(
getString(
R.string.date_placeholder,
String.format("%02d", d),
String.format("%02d", m),
y
)
)
},
year,
month,
day
)
dpd.show()
}
return binding.root
}
private fun setDateText(date: String) {
binding.appointmentDateButton.text = date
}
What am I missing ?
Thanks in advance
Solution 1:[1]
What do you get in setDateText? I copied almost all code and launched. Then got y, m, d inside onDateSet callback. So, a string
getString(
R.string.date_placeholder,
String.format("%02d", d),
String.format("%02d", m),
y
)
should be right (but I don't know what you have put in date_placeholder).
So, this string is passed to setDateText and is written in appointmentDateButton (19 05 2022). I don't know, what happened.
By the way, initial month is incremented by 1. It's a mistake (you open the picker on 19th' June).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
