How to force EditText to accept only numbers?

前端 未结 6 1309
借酒劲吻你
借酒劲吻你 2020-12-08 18:32

how to force the EditText to accept only numbers.?

相关标签:
6条回答
  • 2020-12-08 18:37

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

    0 讨论(0)
  • 2020-12-08 18:38

    If you need support for decimal numbers use this:

      android:inputType="numberDecimal"
    
    0 讨论(0)
  • 2020-12-08 18:52

    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

    0 讨论(0)
  • 2020-12-08 18:56

    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;
            }
        }
    
    0 讨论(0)
  • 2020-12-08 19:03

    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.

    0 讨论(0)
  • 2020-12-08 19:04

    This also works fine:

    android:digits="0123456789"
    
    0 讨论(0)
提交回复
热议问题