How to force EditText to accept only numbers?

2019-01-22 10:52发布

how to force the EditText to accept only numbers.?

5条回答
Emotional °昔
2楼-- · 2019-01-22 11:04

You can use android:inputType="number" in the XML file. You can specify other values such as numberDecimal as well.

Also, you might additionally want to use android:singleLine="true" for a single line Edittext.

Also, look into android:numeric and android:maxLength. maxLength in particular can be useful for setting length limitations.

查看更多
家丑人穷心不美
3楼-- · 2019-01-22 11:07

This is the final solution:

 public static void enforceEditTextUseNumberOnly(EditText field) {
        Typeface existingTypeface = field.getTypeface();
        field.setInputType((InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD));
        field.setTransformationMethod(new NumericKeyBoardTransformationMethod());
        field.setTypeface(existingTypeface);
        if (field.getParent().getParent() instanceof TextInputLayout) {
            ((TextInputLayout) field.getParent().getParent()).setPasswordVisibilityToggleEnabled(false);
        }
    }

  private static class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return source;
        }
    }
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-22 11:18

Or you can add the following:

yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER | 
                          InputType.TYPE_NUMBER_FLAG_DECIMAL |
                          InputType.TYPE_NUMBER_FLAG_SIGNED);

this will accept numbers, float point numbers and negative numbers you can remove any of these as needed

查看更多
做自己的国王
5楼-- · 2019-01-22 11:24

This also works fine:

android:digits="0123456789"
查看更多
Animai°情兽
6楼-- · 2019-01-22 11:25

Use android:inputType="number" in your layout XML

查看更多
登录 后发表回答