I got the same casting error, and, finding a solution, but not finding what worked, I decided to come up with one of mine.
My approach is to use a little trick. Instead of trying to get a class that extends DialogFragment to accept my fragment as DatePickerDialog.OnDateSetListener, I let the DialogFragment class implement the interface and receive a callback. When the callback is called, it passes it along with my fragment, which also implements the same interface. In essence, the DialogFragment class redirects the callback. Here is the DialogFragment class that you could see in many other stackoverflow posts, except that it has a public setListeningActivity () method. setListeningActivity () takes a fragment, action, or indeed any class that implements DatePickerDialog.OnDateSetListener. This is the class to which any callbacks will be redirected to the DialogFragment class.
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { private DatePickerDialog.OnDateSetListener m_listener = null; @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), this, year, month, day); } public void setListeningActivity(DatePickerDialog.OnDateSetListener listener) { m_listener = listener; } @Override public void onDateSet(DatePicker view, int year, int month, int day) { if (m_listener != null) { m_listener.onDateSet(view, year, month, day); } }
The following code is used that uses it:
public class AppPatientInfoFragment extends Fragment implements DatePickerDialog.OnDateSetListener { ... private void setDate(final Calendar calendar) { final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM); ((TextView) m_activity.findViewById(R.id.dob)).setText(dateFormat.format(calendar.getTime())); } public void onDateSet(DatePicker view, int year, int month, int day) { Calendar c = Calendar.getInstance(); c.set(year, month, day); setDate(c); } ... DatePickerFragment fragment = new DatePickerFragment(); fragment.setListeningActivity(AppPatientInfoFragment.this); fragment.show(m_activity.getFragmentManager(), "date");
Basically, what happens is that DatePickerFragment onDateSet () is called because it is the actual callback registered in DatePicker and then DatePickerFragment onDateSet () forwards it to AppPatientInfoFragment onDateSet ().