how to force the EditText to accept only numbers.?
            Asked
            
        
        
            Active
            
        
            Viewed 6.6k times
        
    77
            
            
        - 
                    Please see this link: https://stackoverflow.com/a/70189238/12272687 – Mori Dec 01 '21 at 18:10
 - 
                    amazing answer :) – Mina Farid Dec 02 '21 at 00:47
 
6 Answers
63
            
            
        This also works fine:
android:digits="0123456789"
        Alysson Myller
        
- 1,203
 - 11
 - 13
 
- 
                    2
 - 
                    6according to the question, this is supposed to be accepted answer – Muhammed Refaat Jun 29 '17 at 08:09
 
35
            
            
        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
        Jason Hartley
        
- 2,459
 - 1
 - 31
 - 40
 
        Sergey Benner
        
- 4,421
 - 2
 - 22
 - 29
 
14
            
            
        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.
- 
                    What if my editText appears in the dialog, and thus, I only declare it in .java code? i.e. the dialog editText does not appear in XML file. How can I still achieve this? – Sibbs Gambling Jun 20 '13 at 07:41
 
2
            
            
        If you need support for decimal numbers use this:
  android:inputType="numberDecimal"
        Giedrius Šlikas
        
- 1,073
 - 12
 - 12
 
0
            
            
        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;
        }
    }
        Pier Betos
        
- 1,038
 - 9
 - 17