views:

37

answers:

1

Hi,

I'm using a datepicker in Android to let the user to choose the date. I want it to do one thing if the user picks a date and sets it (I have that working fine) and then to clear a certain text field if the user pushes the cancel button on the datepicker (open up the datepicker but then cancel out of it).

The way I've been trying is by making a

private DatePickerDialog.OnCancelListener mDateCancelListener =
    new DatePickerDialog.OnCancelListener() {
        public void onCancel(DialogInterface dialog) {
            timeClear(); //method that clears text field
        }

    };

then I do

TimePickerDialog timeDialog = new TimePickerDialog(this,
  mTimeSetListener,
  c.get(Calendar.HOUR),
  c.get(Calendar.MINUTE),
  false);
timeDialog.setOnCancelListener(mTimeCancelListener);

to attach the listener.

My problem is that the listener works if the user pushes the back button, but not if they push the cancel button. I tried using a dismiss listener, and that works, except for the fact that it goes off even whether I set or cancel the datepicker!

What do I need to do so something goes off if and only if I push the cancel button on my datepicker?

A: 

Try this:

timeDialog.getButton(TimePickerDialog.BUTTON_NEGATIVE).setOnClickListener(mTimeCancelListener);

(You'll have to change mTimeCancelListener to implement DialogInterface.OnClickListener instead of OnCancelListener)

cristis
Thanks for the response! I'm still having a little trouble. If I make a DialogInterface.OnClickListener and try to use it for the TimePicker, it tells me I need to cast it first. If I do, then the program just crashes when you click the button to open up the TimePicker.If you don't then it sayssetOnClickListener(android.view.View.OnClickListener) in android.view.View cannot be applied to (android.content.DialogInterface.OnClickListener) timeDialog.getButton(TimePickerDialog.BUTTON_NEGATIVE).setOnClickListener(dateTimeClickCancelListener);
Adam
And I tried creating a View.OnClickListner() instead of a DialogInterfaceListener, and the program just crashes when I try to open up the TimePicker dialog
Adam