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

2022-09-01 09:17:12

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

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


}

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


答案 1

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

无论如何。。。让我们假设你有充分的理由按照你的方式去做。在这种情况下,我会使用 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);
    }
}

关于您的活动:

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

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

编辑:以简单的方式进行

您仍然可以使用布局。这就是您如何使用 :mycustomdialogAlertDialog.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();

答案 2

我通过将意图从[对话]广播到[活动]来实现这一点

首先将活动传递到函数中:

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

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

然后准备您的活动,以便在活动中使用 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.
             .....
        }
    }
};

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

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

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