I have a DialogFragment which creates a DatePickerDialog. I'm using a static method called newInstance
to set the initial values in order to use the default empty constructor. However, how am I supposed to set the listener? After the screen rotation, when clicking in the "Done" button, the listener doesn't do anything since it does not exist.
public class DatePickerFragment extends DialogFragment {
public static final String ARG_YEAR = "year";
public static final String ARG_MONTH = "month";
public static final String ARG_DAY = "day";
private OnDateSetListener listener_;
public static DatePickerFragment newInstance(OnDateSetListener listener, int year, int month, int day) {
final DatePickerFragment date_picker = new DatePickerFragment();
date_picker.setListener(listener);
final Bundle arguments = new Bundle();
arguments.putInt(ARG_YEAR, year);
arguments.putInt(ARG_MONTH, month);
arguments.putInt(ARG_DAY, day);
date_picker.setArguments(arguments);
return date_picker;
}
private void setListener(OnDateSetListener listener) {
listener_ = listener;
}
@Override
public Dialog onCreateDialog(Bundle saved_instance_state) {
final Bundle arguments = getArguments();
final int year = arguments.getInt(ARG_YEAR);
final int month = arguments.getInt(ARG_MONTH);
final int day = arguments.getInt(ARG_DAY);
return new DatePickerDialog(getActivity(), listener_, year, month, day);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…