这个问题已经出现好几次了,我已经阅读了所有答案,但我还没有看到真正可靠的方法来处理这个问题。在我的解决方案中,我使用来自调用的侦听器Activity
to the AlertDialog
像这样:
public class MyDialogFragment extends DialogFragment {
public interface MyDialogFragmentListener {
public void onReturnValue(String foo);
}
public void init(boolean someValue)
{
sSomeValue = someValue;
listeners = new ArrayList<MyDialogFragmentListener>();
}
static boolean sSomeValue;
private static ArrayList<MyDialogFragmentListener> listeners;
public void addMyDialogFragmentListener(MyDialogFragmentListener l)
{
listeners.add(l);
}
public void removeMyDialogFragmentListener(MyDialogFragmentListener l)
{
listeners.remove(l);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.title)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
for (MyDialogFragmentListener listener : listeners) {
listener.onReturnValue("some value");
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
// Nothing to do but exit
}
});
if (sSomeValue) {
builder.setMessage(R.string.some_value_message);
} else {
builder.setMessage(R.string.not_some_value_message);
}
// Create the AlertDialog object and return it
return builder.create();
}
}
然后在调用中Activity
,我正常实例化对象,通过传入任何参数init
并设置我的听众。
问题是:当您在对话框打开时旋转设备并更改方向时,Activity
and MyDialogFragment
对象被重新创建。为了确保输入值不会搞砸,我将初始化值设置为static
。这对我来说感觉很奇怪,但由于一次只会出现一个这样的对话框,所以我对此没有意见。问题出在返回值上。原来的监听器将被调用。这很好,因为该对象仍然存在,但如果需要更新 UIActivity
(有),它不会被更新,因为new Activity
实例现在正在控制 UI。
我正在考虑的一种解决方案是铸造getActivity()
在我的对话框类中Activity
并强制对话框本身添加侦听器,而不是调用Activity
做吧。但这感觉就像黑客滚雪球一样。
优雅地处理这个问题的最佳实践是什么?
你是在正确的道路上,我按照建议的方法Android 开发人员 - 使用 DialogFragments 文章.
您创建 DialogFragment 并定义 Activity 将实现的接口,就像上面所做的那样:
public interface MyDialogFragmentListener {
public void onReturnValue(String foo);
}
然后在 DialogFragment 中,当您想要将结果返回到 Activity 时,您将 Activity 投射到界面:
@Override
public void onClick(DialogInterface dialog, int id) {
MyDialogFragmentListener activity = (MyDialogFragmentListener) getActivity();
activity.onReturnValue("some value");
}
然后在Activity
您实现该接口并获取值:
public class MyActivity implements MyDialogFragmentListener {
...
@Override
public void onReturnValue(String foo) {
Log.i("onReturnValue", "Got value " + foo + " back from Dialog!");
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)