Android 如何在警报对话框中添加两个编辑文本字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3426917/
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
How to add two edit text fields in an alert dialog
提问by mbauer14
I am trying to use an alert dialog to prompt for a username and a password in android. I have found this code here:
我正在尝试使用警报对话框在 android 中提示输入用户名和密码。我在这里找到了这个代码:
if (token.equals("Not Found"))
{
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.userpasslayout, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Please Login to Fogbugz");
alert.setMessage("Enter your email and password");
// Set an EditText view to get user input
alert.setView(textEntryView);
AlertDialog loginPrompt = alert.create();
final EditText input1 = (EditText) loginPrompt.findViewById(R.id.username);
final EditText input2 = (EditText) loginPrompt.findViewById(R.id.password);
alert.setPositiveButton("Login", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
input1.getText().toString(); **THIS CRASHES THE APPLICATION**
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
EDIT: I was able to set up the proper layout, but receive an error when I try to access the text field. What is the problem here?
编辑:我能够设置正确的布局,但是当我尝试访问文本字段时收到错误。这里有什么问题?
采纳答案by EboMike
The API Demosin the Android SDK have an example that does just that.
Android SDK 中的API Demos有一个例子可以做到这一点。
It's under DIALOG_TEXT_ENTRY
. They have a layout, inflate it with a LayoutInflater
, and use that as the View.
它在DIALOG_TEXT_ENTRY
. 他们有一个布局,用 膨胀它LayoutInflater
,并将其用作视图。
EDIT: What I had linked to in my original answer is stale. Here is a mirror.
编辑:我在原始答案中链接的内容是陈旧的。这是一面镜子。
回答by ud_an
Check this code in alert box have edit textview when click OK it displays on screen using toast.
在警告框中检查此代码,当单击确定时,它会使用 toast 在屏幕上显示编辑文本视图。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
Toast.makeText(getApplicationContext(), value,
Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
回答by Nandy
Use these lines in the code, because the textEntryView is the parent of username edittext and password edittext.
在代码中使用这些行,因为 textEntryView 是用户名 edittext 和密码 edittext 的父级。
final EditText input1 = (EditText) textEntryView .findViewById(R.id.username);
final EditText input2 = (EditText) textEntryView .findViewById(R.id.password);
回答by D.Snap
/* Didn't test it but this should work "out of the box" */
AlertDialog.Builder builder = new AlertDialog.Builder(this);
//you should edit this to fit your needs
builder.setTitle("Double Edit Text");
final EditText one = new EditText(this);
from.setHint("one");//optional
final EditText two = new EditText(this);
to.setHint("two");//optional
//in my example i use TYPE_CLASS_NUMBER for input only numbers
from.setInputType(InputType.TYPE_CLASS_NUMBER);
to.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout lay = new LinearLayout(this);
lay.setOrientation(LinearLayout.VERTICAL);
lay.addView(one);
lay.addView(two);
builder.setView(lay);
// Set up the buttons
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//get the two inputs
int i = Integer.parseInt(one.getText().toString());
int j = Integer.parseInt(two.getText().toString());
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
builder.show();
回答by Samadhan Medge
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.icon)
.setTitle("Enter the Text:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
/* User clicked OK so do some stuff */
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
回答by Vince Yuan
Check the following code. It shows 2 edit text fields programmatically without any layout xml. Change 'this' to 'getActivity()' if you use it in a fragment.
检查以下代码。它以编程方式显示 2 个编辑文本字段,无需任何布局 xml。如果您在片段中使用它,请将“this”更改为“getActivity()”。
The tricky thing is we have to set the second text field's input type after creating alert dialog, otherwise, the second text field shows texts instead of dots.
棘手的是我们必须在创建警报对话框后设置第二个文本字段的输入类型,否则,第二个文本字段显示文本而不是点。
public void showInput() {
OnFocusChangeListener onFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
// Must use message queue to show keyboard
v.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager= (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(v, 0);
}
});
}
}
};
final EditText editTextName = new EditText(this);
editTextName.setHint("Name");
editTextName.setFocusable(true);
editTextName.setClickable(true);
editTextName.setFocusableInTouchMode(true);
editTextName.setSelectAllOnFocus(true);
editTextName.setSingleLine(true);
editTextName.setImeOptions(EditorInfo.IME_ACTION_NEXT);
editTextName.setOnFocusChangeListener(onFocusChangeListener);
final EditText editTextPassword = new EditText(this);
editTextPassword.setHint("Password");
editTextPassword.setFocusable(true);
editTextPassword.setClickable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setSelectAllOnFocus(true);
editTextPassword.setSingleLine(true);
editTextPassword.setImeOptions(EditorInfo.IME_ACTION_DONE);
editTextPassword.setOnFocusChangeListener(onFocusChangeListener);
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(editTextName);
linearLayout.addView(editTextPassword);
DialogInterface.OnClickListener alertDialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
// Done button clicked
break;
case DialogInterface.BUTTON_NEGATIVE:
// Cancel button clicked
break;
}
}
};
final AlertDialog alertDialog = (new AlertDialog.Builder(this)).setMessage("Please enter name and password")
.setView(linearLayout)
.setPositiveButton("Done", alertDialogClickListener)
.setNegativeButton("Cancel", alertDialogClickListener)
.create();
editTextName.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
editTextPassword.requestFocus(); // Press Return to focus next one
return false;
}
});
editTextPassword.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// Press Return to invoke positive button on alertDialog.
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).performClick();
return false;
}
});
// Must set password mode after creating alert dialog.
editTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
editTextPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
alertDialog.show();
}
回答by Cheryl Simon
Have a look at the AlertDialog docs. As it states, to add a custom view to your alert dialog you need to find the frameLayout and add your view to that like so:
查看 AlertDialog文档。正如它所说,要将自定义视图添加到您的警报对话框,您需要找到 frameLayout 并将您的视图添加到其中,如下所示:
FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT));
Most likely you are going to want to create a layout xml file for your view, and inflate it:
您很可能希望为您的视图创建一个布局 xml 文件,并对其进行扩充:
LayoutInflater inflater = getLayoutInflater();
View twoEdits = inflater.inflate(R.layout.my_layout, f1, false);
回答by devdanke
I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.
我从一个叫 Mossila 的人那里找到了另一组自定义 AlertDialog 的例子。我认为它们比谷歌的例子更好。要快速查看 Google 的 API 演示,您必须将他们的演示 jar(s) 导入您的项目,这可能是您不想要的。
But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here
但是 Mossila 的示例代码是完全独立的。它可以直接剪切并粘贴到您的项目中。它只是有效!然后你只需要根据你的需要调整它。看这里