As far as I am aware, versions prior to Jelly Beans, had Set and Cancel buttons when using TimePickerDialog. Jelly Beans has only Done button.
I could just leave the Done button, and could close the dialog by clicking outside the dialog, but my onTimeSetListener
gets called if pressing Done or outside the dialog.
So I found this stackoverflow question which describes, that there is a bug when using DatePickerDialog. To fix the issue using DatePickerDialog, when initializing I had to set the onDateSetListener
to null
, and implement my own buttons to handle the BUTTON_POSITIVE
(Set) and BUTTON_NEGATIVE
(Cancel) onClick method. Which is fine, because when button Set is called I can access the DatePicker values like this
int yearPicked = dateDlg.getDatePicker().getYear();
int monthPicked = dateDlg.getDatePicker().getMonth();
int dayPicked = dateDlg.getDatePicker().getDayOfMonth();
So there is no need to use onDateSetListener
, but if I would, it would again be called when pressing Set or Cancel.
I tried to use TimePickerDialog the same way, but the problem is, that inside BUTTON_POSITIVE
onClick method, I cannot access the hour and minutes values as before, because TimePickerDialog does not provide TimePicker as DatePickerDialog provides DatePicker. And again if I would used onTimeSetListener
, it would be called by pressing anything.
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int min = cal.get(Calendar.MINUTE);
final TimePickerDialog timeDlg = new TimePickerDialog(PreferencesActivity.this, null, hour, min, true);
// Make the Set button
timeDlg.setButton(DialogInterface.BUTTON_POSITIVE, "Set", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// CANNOT ACCES THE VALUES
Toast.makeText(PreferencesActivity.this, "Set", Toast.LENGTH_SHORT).show();
}
}
});
// Set the Cancel button
timeDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
Toast.makeText(PreferencesActivity.this, "Cancel", Toast.LENGTH_SHORT).show();
}
}
});
timeDlg.show();
TimePickerDialog.OnTimeSetListener
to capture the values entered, but simply don't do anything with them if the negative button is tapped, right? – Coan