如何将侦听器从Fragment传递到DialogFragment [英] How to pass listener from Fragment to DialogFragment
问题描述
我有显示DialogFragment
的Fragment
.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屋!