输入文本对话框 Android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10903754/
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
Input text dialog Android
提问by Luke Taylor
When a user clicks a Button
in my App (which is printed in a SurfaceView
), I'd like a text Dialog
to appear and I would like to store the result in a String
. I'd like the text Dialog
to overlay the current screen. How can I do this?
当用户单击Button
我的应用程序中的 a (打印在 a 中SurfaceView
)时,我希望Dialog
出现一个文本,并将结果存储在String
. 我希望文本Dialog
覆盖当前屏幕。我怎样才能做到这一点?
回答by Aaron
Sounds like a good opportunity to use an AlertDialog.
听起来像是使用AlertDialog的好机会。
As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.
尽管看起来很基本,但 Android 没有内置对话框来执行此操作(据我所知)。幸运的是,这只是在创建标准 AlertDialog 之上的一些额外工作。您只需创建一个 EditText 供用户输入数据,并将其设置为 AlertDialog 的视图。如果需要,您可以使用setInputType自定义允许的输入类型。
If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).
如果您能够使用成员变量,您可以简单地将该变量设置为 EditText 的值,它会在对话框关闭后持续存在。如果不能使用成员变量,则可能需要使用侦听器将字符串值发送到正确的位置。(如果这是您需要的,我可以编辑和详细说明)。
Within your class:
在您的班级中:
private String m_Text = "";
Within the OnClickListener of your button (or in a function called from there):
在按钮的 OnClickListener 中(或从那里调用的函数中):
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
回答by Michal
I will add to @Aaron's answerwith an approach that gives you the opportunity to style the dialog box in a better way. Here is an adjusted example:
我将使用一种方法添加到@Aaron 的答案中,让您有机会以更好的方式设置对话框的样式。这是一个调整后的例子:
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_inpu_password, (ViewGroup) getView(), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);
// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
m_Text = input.getText().toString();
}
});
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
Here is the example layout used to create the EditText dialog:
这是用于创建 EditText 对话框的示例布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/content_padding_normal">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<AutoCompleteTextView
android:id="@+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:imeOptions="actionDone"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
</FrameLayout>
The final result:
最终结果:
回答by bhekman
How about this EXAMPLE? It seems straightforward.
这个例子怎么样?看起来很简单。
final EditText txtUrl = new EditText(this);
// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");
new AlertDialog.Builder(this)
.setTitle("Moustachify Link")
.setMessage("Paste in the link of an image to moustachify!")
.setView(txtUrl)
.setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String url = txtUrl.getText().toString();
moustachify(null, url);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
})
.show();
回答by Phan Van Linh
If you want some space at left
and right
of input
view, you can add some padding like
如果你想在一定的空间left
和right
的input
观点,你可以添加一些填充像
private fun showAlertWithTextInputLayout(context: Context) {
val textInputLayout = TextInputLayout(context)
textInputLayout.setPadding(
resources.getDimensionPixelOffset(R.dimen.dp_19), // if you look at android alert_dialog.xml, you will see the message textview have margin 14dp and padding 5dp. This is the reason why I use 19 here
0,
resources.getDimensionPixelOffset(R.dimen.dp_19),
0
)
val input = EditText(context)
textInputLayout.hint = "Email"
textInputLayout.addView(input)
val alert = AlertDialog.Builder(context)
.setTitle("Reset Password")
.setView(textInputLayout)
.setMessage("Please enter your email address")
.setPositiveButton("Submit") { dialog, _ ->
// do some thing with input.text
dialog.cancel()
}
.setNegativeButton("Cancel") { dialog, _ ->
dialog.cancel()
}.create()
alert.show()
}
dimens.xml
尺寸文件
<dimen name="dp_19">19dp</dimen>
Hope it help
希望有帮助
回答by Magnus W
I found it cleaner and more reusable to extend AlertDialog.Builder
to create a custom dialog class. This is for a dialog that asks the user to input a phone number. A preset phone number can also be supplied by calling setNumber()
before calling show()
.
我发现扩展AlertDialog.Builder
以创建自定义对话框类更简洁、更可重用。这是一个对话框,要求用户输入电话号码。也可以通过在呼叫setNumber()
之前先呼叫来提供预设电话号码show()
。
InputSenderDialog.java
InputSenderDialog.java
public class InputSenderDialog extends AlertDialog.Builder {
public interface InputSenderDialogListener{
public abstract void onOK(String number);
public abstract void onCancel(String number);
}
private EditText mNumberEdit;
public InputSenderDialog(Activity activity, final InputSenderDialogListener listener) {
super( new ContextThemeWrapper(activity, R.style.AppTheme) );
@SuppressLint("InflateParams") // It's OK to use NULL in an AlertDialog it seems...
View dialogLayout = LayoutInflater.from(activity).inflate(R.layout.dialog_input_sender_number, null);
setView(dialogLayout);
mNumberEdit = dialogLayout.findViewById(R.id.numberEdit);
setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if( listener != null )
listener.onOK(String.valueOf(mNumberEdit.getText()));
}
});
setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if( listener != null )
listener.onCancel(String.valueOf(mNumberEdit.getText()));
}
});
}
public InputSenderDialog setNumber(String number){
mNumberEdit.setText( number );
return this;
}
@Override
public AlertDialog show() {
AlertDialog dialog = super.show();
Window window = dialog.getWindow();
if( window != null )
window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
return dialog;
}
}
dialog_input_sender_number.xml
dialog_input_sender_number.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:padding="10dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:paddingBottom="20dp"
android:text="Input phone number"
android:textAppearance="@style/TextAppearance.AppCompat.Large" />
<TextView
android:id="@+id/numberLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/title"
app:layout_constraintLeft_toLeftOf="parent"
android:text="Phone number" />
<EditText
android:id="@+id/numberEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/numberLabel"
app:layout_constraintLeft_toLeftOf="parent"
android:inputType="phone" >
<requestFocus />
</EditText>
</android.support.constraint.ConstraintLayout>
Usage:
用法:
new InputSenderDialog(getActivity(), new InputSenderDialog.InputSenderDialogListener() {
@Override
public void onOK(final String number) {
Log.d(TAG, "The user tapped OK, number is "+number);
}
@Override
public void onCancel(String number) {
Log.d(TAG, "The user tapped Cancel, number is "+number);
}
}).setNumber(someNumberVariable).show();
回答by Studio2bDesigns
@LukeTaylor: I currently have the same task at hand (creating a popup/dialog that contains an EditText)..
Personally, I find the fully-dynamic route to be somewhat limiting in terms of creativity.
FULLY CUSTOM DIALOG LAYOUT :
Rather than relying entirelyupon Code to create the Dialog, you can fully customize it like so :
1) -Create a new Layout Resource
file.. This will act as your Dialog, allowing for full creative freedom!
NOTE: Refer to the Material Design guidelines to help keep things clean and on point.
2) -Give ID's to all of your View
elements.. In my example code below, I have 1 EditText
, and 2 Buttons
.
3) -Create an Activity
with a Button
, for testing purposes.. We'll have it inflate and launch your Dialog!
@LukeTaylor:我目前手头有同样的任务(创建一个包含 EditText 的弹出窗口/对话框)。就
我个人而言,我发现完全动态的路线在创造力方面有些限制。
完全自定义对话框布局:您可以像这样完全自定义它,
而不是完全依赖代码来创建对话框:
1) -创建一个新Layout Resource
文件..这将充当您的对话框,允许完全的创作自由!
注意:请参阅 Material Design 指南以帮助保持清洁和重点。
2) -为所有View
元素提供ID .. 在下面的示例代码中,我有 1EditText
和 2 Buttons
。
3) -创建Activity
一个Button
, 用于测试目的.. 我们会让它膨胀并启动您的对话框!
public void buttonClick_DialogTest(View view) {
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
// Inflate the Layout Resource file you created in Step 1
View mView = getLayoutInflater().inflate(R.layout.timer_dialog_layout, null);
// Get View elements from Layout file. Be sure to include inflated view name (mView)
final EditText mTimerMinutes = (EditText) mView.findViewById(R.id.etTimerValue);
Button mTimerOk = (Button) mView.findViewById(R.id.btnTimerOk);
Button mTimerCancel = (Button) mView.findViewById(R.id.btnTimerCancel);
// Create the AlertDialog using everything we needed from above
mBuilder.setView(mView);
final AlertDialog timerDialog = mBuilder.create();
// Set Listener for the OK Button
mTimerOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View view) {
if (!mTimerMinutes.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "You entered a Value!,", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
}
}
});
// Set Listener for the CANCEL Button
mTimerCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick (View view) {
timerDialog.dismiss();
}
});
// Finally, SHOW your Dialog!
timerDialog.show();
// END OF buttonClick_DialogTest
}
Piece of cake! Full creative freedom! Just be sure to follow Material Guidelines ;)
I hope this helps someone!Let me know what you guys think!
小菜一碟!完全的创作自由!请务必遵循材料指南 ;)
我希望这对某人有所帮助!让我知道你们的想法!
回答by Abdullah Pariyani
It's work for me
这对我有用
private void showForgotDialog(Context c) {
final EditText taskEditText = new EditText(c);
AlertDialog dialog = new AlertDialog.Builder(c)
.setTitle("Forgot Password")
.setMessage("Enter your mobile number?")
.setView(taskEditText)
.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
How to call? (Current activity name)
怎么打电话?(当前活动名称)
showForgotDialog(current_activity_name.this);
showForgotDialog(current_activity_name.this);