Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TimePickerDialog.onTimeSetListener not called

Tags:

android

I'm using the following code to display a TimePickerDialog:

TimePickerDialog dialog = new TimePickerDialog(this, new OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            System.out.println("onTimeSet");
        }
    }, 20, 15, true);
    dialog.setTitle("Test");
    dialog.setButton(TimePickerDialog.BUTTON_POSITIVE, "Done", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            System.out.println("Done");
        }
    });
    dialog.setButton(TimePickerDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            System.out.println("Cancel");
        }
    });
    dialog.show();

On a device running Android 2.3.7, the onTimeSet method doesn't get called (the onClick methods do). On a device running 4.2.2 the onTimeSet does get called like it should.

What is happening here?

like image 683
nhaarman Avatar asked Mar 01 '13 19:03

nhaarman


1 Answers

TimePickerDialog has changed after Android 4.1.1 and there is a bug about cancellation of the both TimePickerDialog and DatePickerDialog. Please read first here. By default you do not need to set positive and negative button. TimePickerDialog and DatePickerDialog handles these for you. So if this cancellation issue is not important for you delete setting of positive and negative button. If you delete those in both version if user clicks OK button your onTimeSet method will be called.

But I recommend until that bug will be fixed use custom made AlertDialog with TimePicker widget;

    final TimePicker timePicker = new TimePicker(this);
    timePicker.setIs24HourView(true);
    timePicker.setCurrentHour(20);
    timePicker.setCurrentMinute(15);

    new AlertDialog.Builder(this)
            .setTitle("Test")
            .setPositiveButton(android.R.string.ok, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Log.d("Picker", timePicker.getCurrentHour() + ":"
                            + timePicker.getCurrentMinute());
                }
            })
            .setNegativeButton(android.R.string.cancel,
                    new OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            Log.d("Picker", "Cancelled!");
                        }
                    }).setView(timePicker).show();
like image 165
cirit Avatar answered Dec 04 '22 17:12

cirit