Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Change button text in DatePickerDialog / TimePickerDialog

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.

like image 225
mburm Avatar asked Apr 05 '13 14:04

mburm


2 Answers

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);
like image 125
javifm Avatar answered Sep 29 '22 04:09

javifm


After create a DatePickerDialog, call this line

datePickerDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Your custom text", datePickerDialog);

Note: just use its dialog without new click listener.

like image 22
cuasodayleo Avatar answered Sep 29 '22 03:09

cuasodayleo