Implementing the DatePicker
or DatePickerDialog
in Android is easy. But when it comes to data storage, I have a problem with those classes:
If you use the spinners (+ or - button) to change the date, everything works fine. The event "Date changed" or "Date set" is called and you can get the values that the user entered.
But when the year is manually entered into the input field (via keyboard) and the user then clicks "Save" in the dialog, there won't be any event called and you won't get that manually entered value.
It only works when the user changes something with the sliders again after manually entering the year. Because when you use the sliders, the events are fired.
Is this normal behaviour? How can I achieve the desired behaviour, namely that an event is fired when the user enteres something manually and then clicks "Save"?
Thanks in advance!
Just clear focus, and android will set the number from manual input.
eg:
DatePicker datePicker = findViewById(R.id.dp);
When saving just like onClick()
, add
datePicker.clearFocus();
This must be working.
I had the same problem and the accepted answer really helped me a lot. My situation is a little different though as I'm using DatePickerDialog
. Here's how the DatePicker
properly worked finally.
Declare the variables first and then define them.
private DatePickerDialog.OnDateSetListener date;
private DatePickerDialog mDatePickerDialog;
private Calendar myCalendar;
// Get the calendar instance
myCalendar = Calendar.getInstance();
// Define the date set listener first.
date = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// Do something with year, monthOfYear and dayOfMonth
}
};
// Now define the DatePickerDialog
mDatePickerDialog = new DatePickerDialog(context, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH));
mDatePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
DatePicker datePicker = mDatePickerDialog.getDatePicker();
// The following clear focus did the trick of saving the date while the date is put manually by the edit text.
datePicker.clearFocus();
date.onDateSet(datePicker, datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth());
}
});
Then inside an onClick
of a button
mDatePickerDialog.show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With