问题
I have I Fragment
that show DialogFragment
.. The DialogFragment
creates and shows a TimePickerDialog
dialog.
I want the calling Fragment to implement the imePickerDialog.OnTimeSetListener
listener. but I don't know how to pass this listener to the Called fragment (The DialogFragment) ..
I have found the following code that passes a listener from ACTIVITY
to the DialogFragment
.
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
// This error will remind you to implement an OnTimeSetListener
// in your Activity if you forget
try {
mListener = (OnTimeSetListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnTimeSetListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), mListener, hour, minute,
true);
}
How to pass it from FRAGMENT
?
回答1:
Can't you just use getTargetFragment and setTargetFragment?
And then first check if the targetFragment is an instance of your Listener:
if (getTargetFragment() instanceof OnTimeSetListener) { mListener.updateTime(); }
来源:https://stackoverflow.com/questions/21338223/how-to-pass-listener-from-fragment-to-dialogfragment