如何'cancel' 按下一个按钮?

How to 'cancel' a button press?

我目前正在尝试使用 AlertDialogs。

目前,我的 AlertDialog 中有一个 EditText,我想将输入限制为仅整数。我使用了基本的 try 和 catch 块来避免应用程序因 NumberFormatException 而崩溃。

但是,我想对其进行设置,以便当用户尝试按下带有错误输入的按钮时,输入不会注册并且对话框不会被取消。

UpperLimitDialog.setPositiveButton(R.string.Positive_Button, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        int RawInput = settings.getInt("UpperLimit", 12);
                        try {
                            RawInput = Integer.parseInt(input.getText().toString());
                        }catch (NumberFormatException se) {
                            Toast.makeText(SettingsMenu.this, "Non-Integer Value, No Input", Toast.LENGTH_SHORT).show();
                        //Here I want the app to not register the click and prevent the dialog box from closing.
                        }
                        editor.putInt("UpperLimit", RawInput);
                        editor.apply();
                        Toast.makeText(SettingsMenu.this, "Set Upper Limit to " + RawInput, Toast.LENGTH_SHORT).show();
                    }
                });

我可以用什么方法来实现这个?

只需在EditText的xml代码中使用:

android:inputType="numberSigned"

这将让用户仅输入整数。希望这对您有所帮助!

这里的基本技巧是使用对话框的 setCancelablefalse 并仅在输入已验证时调用 dismiss()

更多信息在这里:AlertDialog with positive button and validating custom EditText

使用 input to only Integers 可以通过 Java 或 XML 实现 input to only Integers

Java

editText.setInputType(InputType.TYPE_CLASS_NUMBER);

XML

android:inputType = "numberSigned"

这可能对您有所帮助。

如果你限制用户只允许数字那么你可以简单地尝试使用-

android:inputType="number"

如果你想允许浮点数,那么试试 -

android:inputType="numberDecimal"

无论如何,如果您想禁用对话框按钮,请试试这个-

Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setEnabled(false);

对你有用:)