在Android上将值从Dialog传回Activity的可靠方法? [英] Robust way to pass value back from Dialog to Activity on Android?

查看:32
本文介绍了在Android上将值从Dialog传回Activity的可靠方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题已经出现了好几次,我已经阅读了所有的答案,但我还没有看到一个真正可靠的方法来处理这个问题.在我的解决方案中,我使用从调用 ActivityAlertDialog 的侦听器,如下所示:

This question has come up several times and I've read all the answers, but I haven't seen a truly robust way to handle this. In my solution, I am using listeners from the calling Activity to the AlertDialog like so:

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传入任何参数并设置我的监听器.

Then in the calling Activity, I instantiate the object normally, pass in any arguments through init and set my listener.

问题出在:当您在对话框打开时旋转设备并更改方向时,ActivityMyDialogFragment 对象都会重新创建.为了确保输入值不会搞砸,我将初始化值设置为 static.这对我来说感觉很奇怪,但由于一次只会有一个这样的对话,我可以接受.问题出在返回值上.原始侦听器将被调用.这很好,因为该对象仍然存在,但如果需要更新 Activity 上的 UI(存在),它不会被更新,因为 newActivity 实例现在正在控制 UI.

Here's the problem: when you rotate the device and change orientation while the dialog is open, both the Activity and MyDialogFragment objects get re-created. To ensure that the input values don't get screwed up, I am setting my initialized values as static. This feels hacky to me, but since there will only be one such dialog at a time, I am ok with it. Where the problem comes in is with the return value. The original listener will get called. That's fine because the object still exists, but if there is a requirement to update the UI on the Activity (which there is), it won't get updated because the new Activity instance is now controlling the UI.

我正在考虑的一个解决方案是将对话框类中的 getActivity() 强制转换为我的 Activity 并强制对话框本身添加侦听器,而不是调用 <代码>活动做.但这感觉就像是黑客的滚雪球.

One solution I am considering is casting getActivity() in the dialog class to my Activity and forcing the dialog itself to add a listener, rather than having the calling Activity do it. But this just feels like a snowballing of hacks.

优雅地处理这个问题的最佳做法是什么?

What is the best practice for handling this gracefully?

推荐答案

你在正确的轨道上,我按照Android 开发者 - 使用 DialogFragments 文章.

You are on the right track, I follow the method recommended by the Android Developers - Using DialogFragments article.

您创建 DialogFragment 并定义 Activity 将实现的接口,就像您在上面所做的那样:

You create your DialogFragment and define an interface that the Activity will implement, like you have done above with this:

public interface MyDialogFragmentListener {
    public void onReturnValue(String foo);
}

然后在DialogFragment中,当你想将结果返回给Activity时,你将Activity投射到界面中:

Then in the DialogFragment when you want to return the result to the Activity you cast the activity to the interface:

@Override
public void onClick(DialogInterface dialog, int id) {
    MyDialogFragmentListener activity = (MyDialogFragmentListener) getActivity();
    activity.onReturnValue("some value");
}

然后在 Activity 中实现该接口并获取值:

Then in the Activity you implement that interface and grab the value:

public class MyActivity implements MyDialogFragmentListener {
    ...
    @Override
    public void onReturnValue(String foo) {
        Log.i("onReturnValue", "Got value " + foo + " back from Dialog!");
    }
}

这篇关于在Android上将值从Dialog传回Activity的可靠方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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