Java 如何在对话框和活动之间传递值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4279787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:19:45  来源:igfitidea点击:

How can I pass values between a Dialog and an Activity?

javaandroidvariablesdialog

提问by Sheehan Alam

I am asking the user for input via a Dialog:

我要求用户通过对话框输入:

package com.android.cancertrials;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class CustomDialog extends Dialog  {


    private String name;
//    private ReadyListener readyListener;
     public static EditText etName;
     public String zip;

    public CustomDialog(Context context, String name) {
        super(context);
        this.name = name;
//        this.readyListener = readyListener;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mycustomdialog);
        setTitle("Enter the Zip Code ");
        Button buttonOK = (Button) findViewById(R.id.ok);
        buttonOK.setOnClickListener(new OKListener());
        etName = (EditText) findViewById(R.id.EditZip);
    }

    private class OKListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
//            readyListener.ready(String.valueOf(etName.getText()));
            CustomDialog.this.dismiss();
        }
    }


}

When the user hits OK, how can I pass the value that was entered in the textbox, back to a member variable in the Activity that launched it?

当用户点击 OK 时,如何将在文本框中输入的值传递回启动它的 Activity 中的成员变量?

采纳答案by Cristian

You can do that in different ways... actually, if your dialog has only an "OK" button to dismiss, why don't you just create a custom dialog using the AlertDialog.Builderclass instead of subclassing Dialog?

你可以用不同的方式做到这一点......实际上,如果你的对话框只有一个“确定”按钮可以关闭,你为什么不使用AlertDialog.Builder类而不是子类创建一个自定义对话框Dialog

Anyway... let's suppose you have good reasons to do it the way you did it. In that case, I'd use the ObserverPattern. Something like this:

无论如何......让我们假设你有充分的理由按照你的方式去做。在这种情况下,我会使用 ObserverPattern。像这样的东西:

public class CustomDialog extends Dialog  {


    private String name;
     public static EditText etName;
     public String zip;
    OnMyDialogResult mDialogResult; // the callback

    public CustomDialog(Context context, String name) {
        super(context);
        this.name = name;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // same you have
    }

    private class OKListener implements android.view.View.OnClickListener {
        @Override
        public void onClick(View v) {
            if( mDialogResult != null ){
                mDialogResult.finish(String.valueOf(etName.getText()));
            }
            CustomDialog.this.dismiss();
        }
    }

    public void setDialogResult(OnMyDialogResult dialogResult){
        mDialogResult = dialogResult;
    }

    public interface OnMyDialogResult{
       void finish(String result);
    }
}

On your activity:

关于您的活动:

CustomDialog dialog;
// initialization stuff, blah blah
dialog.setDialogResult(new OnMyDialogResult(){
    public void finish(String result){
        // now you can use the 'result' on your activity
    }
});

Reading your code it seems you already tried something similar.

阅读您的代码,您似乎已经尝试过类似的方法。

Edit: doing it the easy way

编辑:用简单的方法做

You can still use your mycustomdialoglayout. And this is how you would use the AlertDialog.Builder:

您仍然可以使用您的mycustomdialog布局。这就是您将如何使用AlertDialog.Builder

LayoutInflater inflater = LayoutInflater.from(YourActivity.this);
final View yourCustomView = inflater.inflate(R.layout.mycustomdialog, null);

final TextView etName = (EditText) yourCustomView.findViewById(R.id.EditZip);
AlertDialog dialog = new AlertDialog.Builder(YourActivity.this)
    .setTitle("Enter the Zip Code")
    .setView(yourCustomView)
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            mSomeVariableYouHaveOnYourActivity = etName.getText().toString();
        }
    })
    .setNegativeButton("Cancel", null).create();
dialog.show();

回答by Robert

I achieve this through broadcasting intent from [dialog]to [activity].

我通过从[dialog][activity]广播意图来实现这一点。

First passing the activity into the function:

首先将活动传递给函数:

public class DialogFactory {

    public static AlertDialog addSomeDialog(Activity activity) {
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                  if (SOMETHING_IS_TRUE) {

                      // prepare your parameters that need to be sent back to activity
                      Intent intent = new Intent(IntentAction.INTENT_ADD_TASK);
                      intent.putExtra(IntentConst.PARAM_A, aInput);
                      intent.putExtra(IntentConst.PARAM_B, bInput);
                      activity.sendBroadcast(intent);

                      Toast.makeText(activity, "Something is TRUE!", Toast.LENGTH_SHORT).show();
                  } else {
                      Toast.makeText(activity, "Something NOT TRUE!", Toast.LENGTH_SHORT).show();
                  }
            }
        });
    }
}

Call above function when some option menu or button clicked in your activity.

在您的活动中单击某些选项菜单或按钮时调用上述函数。

Then prepare your activity to receive the intent with BroadcastReceiver in the activity:

然后准备您的活动以在活动中使用 BroadcastReceiver 接收意图:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == IntentAction.INTENT_ADD_TASK) {
             // Do whatever you want to refresh the layout or anything in the activity
             // or even ask fragments inside to act upon it.
             .....
        }
    }
};

Don't forget to register & un-register the receiver:

不要忘记注册和取消注册接收器:

@Override
protected void onPause() {
    unregisterReceiver(mReceiver);
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mReceiver, new IntentFilter(IntentAction.INTENT_ADD_TASK));
}