Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimePickerDialog cancel button

Tags:

android

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() and returns to the activity that called the TimePickerActivity. I want it to finish and return if the Cancel button is clicked but can't find any way to do this. I have googled and tried out severall suggestions but none of them seem to work. Any simple way to do this?

like image 654
ron Avatar asked Dec 07 '22 23:12

ron


2 Answers

Just pass an onCancelListener to TimePicker.setOnCancelListener()

edit: After Ron's problems with implementation I decided to actually test myself the code (I answered just looking at the API) and I discovered than even if the code is correct (I suppose you had a typo somewhere as my code compiles ok), when clicking the cancel button it didn't respond as intended...

It appears that when you click cancel button the Dialog doesn't call the cancel() method that fires the OnCancelListener as it would seem the obvious, but the dismiss() method that fires an OnDismissListener, pretty weird...

So this code is working fine for me:

TimePickerDialog.OnTimeSetListener mTimeSetListener = new OnTimeSetListener() {
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        //time set stuff
    }
};
TimePickerDialog myTPDialog = new TimePickerDialog(this,mTimeSetListener,0,0,false);
myTPDialog.setOnDismissListener(new OnDismissListener() {
    public void onDismiss(DialogInterface dialog) {
        // Cancel code here
    }
});
myTPDialog.show();

all credits to this SO answer...

like image 76
maid450 Avatar answered Jan 02 '23 11:01

maid450


here is how I did it:

TimePickerDialog tp = new TimePickerDialog(this, mTimeSetListener, 0, 0, false);
tp.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which)
    {
        if (which == DialogInterface.BUTTON_NEGATIVE)
        {
            tbTimer.setChecked(false);
        }
    }
});
like image 29
binW Avatar answered Jan 02 '23 10:01

binW