Skip to content Skip to sidebar Skip to footer

How To Allow Only Specific Number In Edittext?

am trying to put only a specific value in my edit text. I have used this this my layout. android:digits='0123468' however, i also do not want that number 1 and 3 should w

Solution 1:

This could be an aproach:

<EditText
android:id="@+id/edtNumber"android:digits="0123456789"android:inputType="number" />

And if you want to discard '1' and '3' you could get input number like this:

Integer.parseInt(edtNumber.getText().toString())

and compare it with values you don't want.


Also if for some reason you want to use decimals do this:

<EditText
android:id="@+id/edtNumberDecimal"android:digits="0123456789."android:inputType="numberDecimal" />

Solution 2:

Use regular expressions.

@OverridepublicvoidafterTextChanged(Editable s) {
      Stringtext= s.toString();
      intlength= text.length();

      Patternpattern= Pattern.compile("(?s)\\d|[024-9]{2,}");

      if(length > 0 && !Pattern.matches(pattern, text)) {
           s.delete(length - 1, length);
      }
}

Post a Comment for "How To Allow Only Specific Number In Edittext?"