Android: Change button text in DatePickerDialog / TimePickerDialog

mburm picture mburm · Apr 5, 2013 · Viewed 7k times · Source

I have got a DatePickerDialog. In the default configuration it works fine.

DatePickerDialog dialog = new DatePickerDialog(
    view.getContext(),
    new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker picker, int year, int monthOfYear, int dayOfMonth) {
            // do something
        }
    },
    startDate.getYear(),
    startDate.getMonth() - 1,
    startDate.getDay()
);

enter image description here

Now I want to change the text of the buttons. I try it with the following code:

dialog.setButton(DatePickerDialog.BUTTON_POSITIVE, "New Label", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
        // do something
    }
});

Now my problem is to get the date from the datepicker control. The DateSetListener will not be called by click on the button. How is it possible to get the date via the DateSetListener? Another possibility to get the date is about

public void onClick(DialogInterface dialog, int which) {
    int year = ((DatePickerDialog) dialog).getDatePicker().getYear();
    int month = ((DatePickerDialog) dialog).getDatePicker().getMonth();
    int day = ((DatePickerDialog) dialog).getDatePicker().getDayOfMonth();
}

But this seems to be a unnecessary complicated way.

For the TimePickerDialog this alternative way will not work because I find no way to get the timepicker control. Therefore I need to use the TimeSetListener but I cannot find the possibility (like for the datepicker).

Thanks for any response.

Answer

puro_nervio picture puro_nervio · May 16, 2013

I supose that this will work on DatePicker, it works for me in TimePicker:

The listener:

TimePickerDialog.OnTimeSetListener mTimeSetListenerIni =
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(android.widget.TimePicker view,
                            int hourOfDay, int minute) {
                        Log.i("","Initial: "+hourOfDay+":"+minute);
                    }
                };

TimePickerDialog yourFragment = new TimePickerDialog(this, mTimeSetListenerIni, hour, minute, true);
yourFragment.setButton(DialogInterface.BUTTON_POSITIVE, "OK", yourFragment);
yourFragment.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", yourFragment);