How to pass listener from Fragment to DialogFragment

亡梦爱人 提交于 2020-01-02 08:34:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!