Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Handle backspace on InputFilter

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;
}
like image 908
user2287966 Avatar asked Jan 09 '23 09:01

user2287966


1 Answers

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 "";
    }

}

like image 107
user2287966 Avatar answered Jan 21 '23 06:01

user2287966