Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert Dialog with a numeric EditText field

I am alerting the user with and alert dialog box that has an EditText field.

AlertDialog.Builder alert = new AlertDialog.Builder(this);
    db.open();
    Cursor f = db.getTitle(position + 1);
    alert.setTitle("Age");
    alert.setMessage("New age?");

    // Set an EditText view to get user input
    final EditText input = new EditText(this);
    alert.setView(input);
    input.setText(f.getString(3));
    db.close();
    alert.setPositiveButton("Change",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    String age = input.getText().toString();
                    db.open();
                    Cursor ff = db.getTitle(position + 1);
                    db.updateTitle(ff.getLong(0), ff.getString(1),
                            ff.getString(2), age, ff.getString(4),
                            ff.getString(5));
                    db.close();
                    details();
                    age();
                }
            });

    alert.setNegativeButton("Keep", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // do nothing
        }
    });
    alert.show();

Is there a way to only allow the user to input a two digit number (no letters, symbols, etc)?

like image 326
Raddfood Avatar asked Nov 15 '25 03:11

Raddfood


1 Answers

I suggest you set some input filters and a key listener on the EditText, like so:

input.setFilters(new InputFilter[] {
    // Maximum 2 characters.
    new InputFilter.LengthFilter(2),
    // Digits only.
    DigitsKeyListener.getInstance(),  // Not strictly needed, IMHO.
});

// Digits only & use numeric soft-keyboard.
input.setKeyListener(DigitsKeyListener.getInstance());
like image 99
Ozone Avatar answered Nov 17 '25 18:11

Ozone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!