问题
I created an InputFilter for an EditText component that only allows doubles within a range (e.g. from 1.5 to 5.5). Everything worked fine until I deleted the decimal point:
I typed 1.68 and then deleted the decimal point. The value in the text field became 168, which is obviously outside the range.
Here is a simplified version of my filter
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (isValid(dest.toString() + source.toString())) {
//input is valid
return null;
}else{
//The input is not valid
return "";
}
}
private boolean isValid(String input) {
Double inputValue = Double.parseDouble(input);
boolean isMinValid = (1.5 <= inputValue);
boolean isMaxValid = (5.5 >= inputValue);
return isMinValid && isMaxValid;
}
回答1:
I solved my problem. Here is the solution in case someone else needs it:
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (isValid(dest.toString() + source.toString())) {
//input is valid
return null;
}else{
//The input is not valid
if (source.equals("") && dest.toString().length() != 1) {
//backspace was clicked, do not accept that change,
//unless user is deleting the last char
CharSequence deletedCharacter = dest.subSequence(dstart, dend);
return deletedCharacter;
}
return "";
}
}
回答2:
When you are finished entering data in the edit text, you have to trigger knowing you have finished entering data and now have to check the input. For example by adding input test button, or for example when the edit text field loses focus.
来源:https://stackoverflow.com/questions/27151389/android-handle-backspace-on-inputfilter