问题
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 work in my edit text.
Sample; enter 32... it gives me a list of items but enter 3 should not allow me to do something.
Can someone help me on this?
回答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" />
回答2:
Use regular expressions.
@Override
public void afterTextChanged(Editable s) {
String text = s.toString();
int length = text.length();
Pattern pattern
= Pattern.compile("(?s)\\d|[024-9]{2,}");
if(length > 0 && !Pattern.matches(pattern, text)) {
s.delete(length - 1, length);
}
}
来源:https://stackoverflow.com/questions/36337953/how-to-allow-only-specific-number-in-edittext