如何将侦听器从Fragment传递给DialogFragment

时间:2014-01-24 17:00:18

标签: android android-fragments listener android-dialogfragment

我有Fragment,显示DialogFragment .. DialogFragment创建并显示TimePickerDialog对话框。

我希望调用Fragment来实现imePickerDialog.OnTimeSetListener侦听器。但我不知道如何将这个监听器传递给Called片段(The DialogFragment)..

我找到了以下代码,将侦听器从ACTIVITY传递到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);
}

如何从FRAGMENT传递它?

1 个答案:

答案 0 :(得分:1)

你不能只使用getTargetFragment和setTargetFragment吗?

然后首先检查targetFragment是否是您的Listener的实例:

  

if(getTargetFragment()instanceof OnTimeSetListener){   mListener.updateTime(); }