问题描述
我创建了包含OnDialogClickListener参数的ErrorDialogFragment.
I have created ErrorDialogFragment which contains OnDialogClickListener parameter.
需要显示ErrorDialogFragment的所有其他Fragment或Activity都通过ErrorDialogFragment中的公共方法设置OnDialogClickListener.同时,所有这些活动和片段都实现了OnDialogClickListener.
Every other Fragment or Activity that needs to show ErrorDialogFragment sets OnDialogClickListener via public method in ErrorDialogFragment. In the same time, all those activities and fragments implements OnDialogClickListener .
如果在显示ErrorDialogFragment时用户从应用程序退出,并在一段时间后返回(从内存中删除应用程序),则会出现问题.如果用户单击片段选项,它将被强制关闭,因为未设置OnDialogClickListener.
Problem occurs if user exits from application when ErrorDialogFragment is showed, and returns after a while (app is removed from memory). If user clicks on fragment options it will force close, because OnDialogClickListener is not set.
我对活动侦听器片段模式不满意,我该如何解决(应用程序已经在beta中.不能接受大的模式更改.
Am i wrong with with activity-listener-fragment pattern, and how do i solve this (application is in beta already.. big pattern change is not acceptable.
例如:
接口:
public interface OnDialogClickListener {
public void OnPositiveClick(int key, Object... args);
public void OnNegativeClick(int key, Object... args);
}
活动:
public class Home extends FragmentActivity implements TabListener, ServiceConnection, OnDialogClickListener {
.
.
.
@Override
public void OnPositiveClick(int key, Object... args) {
//some actions
}
@Override
public void OnNegativeClick(int key, Object... args) {
//some actions
}
片段:
public class ErrorDialogFragment extends DialogFragment implements OnClickListener {
OnDialogClickListener OnDialogClickListener = null;
.
.
.
public void setDialogListener(OnDialogClickListener listener)
{
OnDialogClickListener = listener;
}
@Override
public void onClick(DialogInterface dialog, int which) {
if(OnDialogClickListener != null){
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
this.dismiss();
OnDialogClickListener.OnPositiveClick(KEY, args);
break;
default:
this.dismiss();
OnDialogClickListener.OnNegativeClick(KEY, args);
break;
}
}
else
this.dismiss();
}
推荐答案
您可以更好地在DialogFragment#onAttach(Activity)
回调中进行设置,如下所示:
You're way off better setting it in DialogFragment#onAttach(Activity)
callback like this:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnDialogClickListener = (OnDialogClickListener) activity;
} catch(ClassCastException e) {
throw new ClassCastException(activity.toString() + "must implement" + OnDialogClickListener.class.getSimpleName());
}
}
@Override
public void onDetach() {
super.onDetach()
mOnDialogClickListener = null;
}
最后,显然,使您的Activity
实现OnDialogClickListener
And finally, obviously, make your Activity
implements OnDialogClickListener
这篇关于在应用程序还原时在片段中设置侦听器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!