Search code examples
javaandroidandroid-edittextnumbersandroid-inputtype

Android Edit Text - Input Type Number not setting max value


So what I would like is a very simple edit text with input type number or decimal that has the following aspects.

Number Edit Text:
You can only type up to Long.MAX_VALUE / Long.MIN_VALUE, so I can cast to a long without modifying the user's input.

Number Decimal Edit Text:
You can only type a number convertible to a double.

Also I do not need to use BigDecimal or BigIntegers, I need primitive values. Finally, I know this was already asked here but it is not what I want. There are some different requirements.


Solution

  • I managed to do it with a custom class extending EditText that adds a TextWatcher in the constructor. In the afterTextChanged method it tries to convert that to a long. If it fails (NumberFormatException) it sets the number to the respective min / max value (based on the "-" sign at the beggining of the number).