在Android上将对话框的值传回给Activity的强大方法? [英] Robust way to pass value back from Dialog to Activity on Android?

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

问题描述

这个问题已经出现了好几次,我已经阅读了所有的答案,但是我还没有看到一个真正有效的方法来处理这个问题。在我的解决方案中,我正在使用调用活动 AlertDialog 的听众:

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();
    }
}

然后在调用活动,我正常地实例化对象,通过 init 传递任何参数,并设置我的监听器。

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

以下是问题:旋转设备并在对话框打开时更改方向,$ code>活动和 MyDialogFragment 对象重新创建。为了确保输入值不会被弄乱,我将初始化值设置为 static 。这对我来说感觉很奇怪,但是由于一次只会有一个这样的对话,所以我可以确定。问题出现在哪里是返回值。原来的听众将被调用。这很好,因为对象仍然存在,但是如果需要更新活动(有)的UI,则不会更新,因为 活动实例正在控制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()在我的活动的对话框类中,并强制对话框本身添加一个监听器,而不是调用活动做到这一点。

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中将结果返回给您投放的活动接口的活动:

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");
}

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

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上将对话框的值传回给Activity的强大方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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