我要求用户通过对话框输入:
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();
}
}
}
当用户点击确定时,我如何将在文本框中输入的值传递回启动它的 Activity 中的成员变量?
原文由 Sheehan Alam 发布,翻译遵循 CC BY-SA 4.0 许可协议
你可以用不同的方式做到这一点……实际上,如果你的对话框只有一个“确定”按钮可以关闭,你为什么不使用
AlertDialog.Builder
类而不是子类创建一个自定义对话框Dialog
?无论如何……让我们假设你有充分的理由按照你的方式去做。在这种情况下,我会使用 ObserverPattern。是这样的:
关于您的活动:
阅读您的代码,您似乎已经尝试过类似的方法。
编辑:以简单的方式进行
您仍然可以使用您的
mycustomdialog
布局。这就是您使用AlertDialog.Builder
的方式: