Alert Dialog with a numeric EditText field

ⅰ亾dé卋堺 提交于 2019-12-12 16:26:03

问题


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


回答1:


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



回答2:


If it must be numbers, why don't you just use spinners or drop-down-list to represent? it should be more intuitive than textbox.



来源:https://stackoverflow.com/questions/4551368/alert-dialog-with-a-numeric-edittext-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!