I have an activity - TimePickerActivity - which creates a TimePickerDialog. I have a onTimeSetListener which responds to the Set button at the end of which it calls finish(
My solution is based on @maid450 answer, remark of @Fortega and a fact that OnDismissListener is called (usually in last turn) on any click when a time picker dialog is shown.
private int timeSetStatus; // A clicked button result.
...
timeSetStatus = 0;
final Calendar calendar = Calendar.getInstance();
final TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
timeSetStatus = 1;
// Other actions.
}
}, calendar.get(Calendar.HOUR_OF_DAY), 0, true);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
timeSetStatus = 2;
// Actions on clicks outside the dialog.
}
});
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
if (timeSetStatus == 0) {
// Actions on Cancel button click.
}
}
});
dialog.show();