ChatGPT解决这个技术问题 Extra ChatGPT

输入文本对话框 Android

当用户在我的应用程序中单击 Button(打印在 SurfaceView 中)时,我希望出现文本 Dialog,并且我希望将结果存储在 String 中。我希望文本 Dialog 覆盖当前屏幕。我怎样才能做到这一点?


A
Aaron

听起来是使用 AlertDialog 的好机会。

看起来很基本,Android 没有内置对话框来执行此操作(据我所知)。幸运的是,这只是在创建标准 AlertDialog 之上的一点额外工作。您只需创建一个 EditText 供用户输入数据,并将其设置为 AlertDialog 的视图。如果需要,您可以使用 setInputType 自定义允许的输入类型。

如果您能够使用成员变量,您可以简单地将变量设置为 EditText 的值,并且在对话框关闭后它将保持不变。如果不能使用成员变量,则可能需要使用侦听器将字符串值发送到正确的位置。 (如果这是您需要的,我可以编辑和详细说明)。

在你的班级内:

private String m_Text = "";

在按钮的 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();

我有一个不断更新和呈现屏幕对象的线程,我在屏幕对象的更新方法中调用 builder.show() 方法。
哦。如果您在工作线程上,请尝试将 builder.show();使用 runOnUiThread 调用,类似于此示例:stackoverflow.com/a/3134720/1098302 或者最好将上面的所有代码(创建 AlertDialog)放在一个单独的方法中,然后从 runOnUiThread 中调用该方法。
谢谢你。那挺好的。但是,有一个小问题。需要声明 global Context, Context cont;,然后将 alertdialog 中的“this”替换为 cont。 AlertDialog.Builder builder = new AlertDialog.Builder(cont);最后的 EditText 输入 = new EditText(cont);
我认为不是为上下文创建全局变量,而是可以传递上下文,例如:“MainActivity.this”(您需要将文本“MainActivity”替换为要使用的活动类名称)。
可能值得注意的是,与大多数 Android UI 一样,这都是异步的……这意味着它不会等待用户点击 OK,除非你有什么东西可以让你进入下一步……
S
Stevoisiak

我将在 @Aaron's answer 中添加一种方法,让您有机会以更好的方式设置对话框样式。这是一个调整后的例子:

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

这是用于创建 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>

最终结果:

https://i.stack.imgur.com/03TwW.png


绝妙的解决方案!我刚刚用 findViewById(android.R.id.content) 替换了 getView(),一切都像魅力一样。非常感谢分享 :)
请记住使用 (ViewGroup) 投射 findViewById!
“此处不允许使用元素 AutoCompleteTextView...”
@JPerk:android.R.id.content 为您提供视图的根元素。请参考:stackoverflow.com/a/12887919/1911652
只是想知道,但是 @dimen/content_padding_normal 的值是多少?
N
Nachi

这个EXAMPLE怎么样?这似乎很简单。

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

与亚伦的几乎相同,但锁住了建造者。个人喜好问题,因为两者都可以正常工作。
L
Linh

如果您想在 input 视图的 leftright 留出一些空间,您可以添加一些填充,例如

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

尺寸.xml

<dimen name="dp_19">19dp</dimen>

https://i.stack.imgur.com/WooAe.png

希望有帮助


resources 是什么?
A
Abdullah

这对我有用

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

怎么打电话? (当前活动名称)

showForgotDialog(current_activity_name.this);


M
Magnus

我发现扩展 AlertDialog.Builder 以创建自定义对话框类更简洁且更可重用。这是一个要求用户输入电话号码的对话框。还可以通过在调用 show() 之前调用 setNumber() 来提供预设电话号码。

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

<?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>

用法:

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

S
Studio2bDesigns

@LukeTaylor:我目前手头有相同的任务(创建一个包含 EditText 的弹出窗口/对话框)..
就我个人而言,我发现完全动态的路线在创造力方面有些限制。

完全自定义对话框布局:

您可以完全自定义对话框,而不是完全依赖代码来创建对话框像这样:

1) - 创建一个新的 Layout Resource 文件。这将充当您的对话框,允许完全的创作自由!
注意:请参阅 Material Design 指南以帮助保持简洁和准确。

2) - 为您的所有 View 元素提供 ID。在下面的示例代码中,我有 1 个 EditText 和 2 个 Buttons

3) - 创建一个带有 ButtonActivity,用于测试目的。我们将让它膨胀并启动您的对话框!

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
}

小菜一碟!充分的创作自由!请务必遵循材料指南;)我希望这对某人有所帮助!让我知道你们的想法!


只是好奇为什么(-1)投反对票?我提供的逻辑完全按照预期和描述的方式工作。我觉得这是对这篇文章的一个很好的补充,但还没有提到,而且是一个完美的替代解决方案。但是,如果您有正当理由反对我提供的信息,如果您能提供一些背景来说明您为什么这样做,那么我和其他人可以学习和理解推理。在学习过程中有用和有帮助 - 但只有在背后有背景的情况下。
m
mxkmn

它是 @Studio2bDesigns' answer 的 Kotlin 实现,它提供了通过自定义布局创建文本输入对话框的能力。我将它用于设置对话框,这就是我使用不同变量名的原因。

val alertDialog = AlertDialog.Builder(this).create()
val settingsBinding = SettingsDialogBinding.inflate(layoutInflater) // SettingsDialogBinding provided by View binding
alertDialog.setView(settingsBinding.root)

settingsBinding.etLink.setText("Some text here")

settingsBinding.btnSave.setOnClickListener {
  if (settingsBinding.etLink.text.toString().isNotBlank()) {
    Toast.makeText(this, "You entered a Value!", Toast.LENGTH_LONG).show()
  } else {
    Toast.makeText(this, "Please enter a Value!", Toast.LENGTH_LONG).show()
  }
}
settingsBinding.btnCancel.setOnClickListener {
  alertDialog.dismiss() // close the dialog
}

alertDialog.show()