如何将侦听器从Fragment传递到DialogFragment [英] How to pass listener from Fragment to DialogFragment

查看:123
本文介绍了如何将侦听器从Fragment传递到DialogFragment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有显示DialogFragmentFragment.DialogFragment创建并显示TimePickerDialog对话框.

I have I Fragment that show DialogFragment .. The DialogFragment creates and shows a TimePickerDialog dialog.

我希望调用Fragment实现imePickerDialog.OnTimeSetListener侦听器.但我不知道如何将此侦听器传递给被调用的片段(The DialogFragment)..

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) ..

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

如何从FRAGMENT通过它?

推荐答案

您不能只使用getTargetFragment和setTargetFragment吗?

Can't you just use getTargetFragment and setTargetFragment?

然后首先检查targetFragment是否是您的侦听器的实例:

And then first check if the targetFragment is an instance of your Listener:

if(OnTimeSetListener的getTargetFragment()实例){ mListener.updateTime(); }

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

这篇关于如何将侦听器从Fragment传递到DialogFragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆