2

I'm trying to make a custom DatePickerDialog class that will fire the onDateSet Listener Callback, but instead of containing the "Day" "Month" and "year" values, I want to overload the constructor to contain a LocalDate from java.time instead. I know I can convert the values to and back from each other, but for learning purposes, I would like to do it directly.

I've never extended/overloaded an Android class before, so I'm not sure which steps to take.
I have tried to create a CustomDatePickerDialog class that extends the DatePickerDialog, but the default constructor must still contain the super-Constructor, so that does not really help me.

Another thought was that I could copy the Android Class (DatePickerDialog) into my local App, change the Name and Constructor in there and then use my new local class. The problem with that was, that I could not find the source code for the DatePickerDialog (or any classes for that matter). I also feel like this is a kind of round-about way to solve the issue.

What is the best way to change the Constructor for a custom Class that extends a default android class?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
fogx
  • 1,749
  • 2
  • 16
  • 38

1 Answers1

2

Something like (not tested)

public class CustomDatePickerDialog extends DatePickerDialog {

    public static interface CustomOnDateSetListener {
        void onDateSet(DatePicker view, LocalDate date);
    }

    public CustomDatePickerDialog(Context context,
            CustomOnDateSetListener listener, LocalDate date) {
        super(context, adaptListener(listener),
                date.getYear(), date.getMonthValue() - 1, date.getDayOfMonth());
    }

    private static OnDateSetListener adaptListener(CustomOnDateSetListener customListener) {
        return new OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                customListener.onDateSet(view, LocalDate.of(year, month + 1, dayOfMonth);
            }
        }
    }

}

The most complicated part is the custom listener. I am declaring a new interface for it. We need to pass an old-fashioned DatePickerDialog.OnDateSetListener to the superclass, so in adaptListener I am building one that when called forwards the call to then listener passed into the constructor as argument.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161