How to 'cancel' a button press?

I am currently trying to work with AlertDialogs.

Currently, I have an EditText in my AlertDialog, and want to restrict the input to only Integers. I have used a basic try and catch block to avoid the app crashing form a NumberFormatException.

However, I want to set it up so that when the user tries to press the button with the incorrect input, the input does not register and the Dialog is not cancelled.

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

What method can I use to achieve this?

Upvotes: 1

Views: 83

Answers (4)

Paras Sidhu
Paras Sidhu

Reputation: 670

Simply use in EditText's xml code:

android:inputType="numberSigned"

This will let user input only integers. Hope this helps!

Upvotes: 0

Amit Bhati
Amit Bhati

Reputation: 1405

If you restrict user to allow only number then you can simply try with-

android:inputType="number"

and if you want to allow with floating number then try with-

android:inputType="numberDecimal"

and in any case if you want to disable dialog button then try this-

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

will work for you :)

Upvotes: 1

Sathish Kumar J
Sathish Kumar J

Reputation: 4345

Use can acheive input to only Integers this by both Java or XML.

Java

editText.setInputType(InputType.TYPE_CLASS_NUMBER);

XML

android:inputType = "numberSigned"

this may helps you in both way.

Upvotes: 2

Lino
Lino

Reputation: 6160

The basic trick here is to use the dialog's setCancelable to false and call dismiss() only when the input has been validated.

More info here: AlertDialog with positive button and validating custom EditText

Upvotes: 3

Related Questions