As the title says, I set up an EditText in my activity and want to limit the input to only numbers. However, it doesn't matter if it is a decimal number or integer. I do require the number of digits is limited at 3. For example, the input of '123', '1.23', '12.3' are all legit input.
'1234', '123.', '.123' are all illegal input.
I have tried to set up
android:inputType = "numberDecimal"
in the xml file.
And set the max length to 4.
edit:
I also tried following code:
InputFilter filter = new InputFilter() {
//^\-?(\d{0,5}|\d{0,5}\.\d{0,3})$
//^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (end > start) {
// adding: filter
// build the resulting text
String destinationString = dest.toString();
String resultingTxt = destinationString.substring(0, dstart) + source.subSequence(start, end) + destinationString.substring(dend);
// return null to accept the input or empty to reject it
return resultingTxt.matches("^\\-?(\\d{0,3}|\\d{0,2}\\.\\d{0,1}|\\d{0,1}\\.\\d{0,2})$") ? null : "";
}
return null;
}
};
I did modified the regex from the sample code mentioned by @Suman Dash. My understanding of the regex
^\-?(\d{0,3}|\d{0,2}\.\d{0,1}|\d{0,1}\.\d{0,2})$
is to allow certain pattern of number input such as #.##, ##.# and ###. When I test the code, the pattern #.## and ##.# are working fine, but the pattern ### also allow input like ".##", for example, ".88" as legit input. And it treats the decimal point as a legit number, so I can only input ".88", not ".123". Anyway, I don't want any number starts with the decimal point. How can I eliminate that? What's the best way to achieve this goal? Thanks!