Android: referring to backspace on InputFilter

I have created an InputFilter for the EditText component that only allows doubles within a range (e.g. 1.5 to 5.5). Everything worked fine until I removed the decimal point:

I typed in 1.68 and then removed the decimal point. The value in the text box is now 168, which is clearly out of 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;
}

      

+3


source to share


2 answers


I solved my problem. Here's a solution in case anyone 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 "";
    }

      



}

+6


source


When you finish entering data into the edit text, you need to ask that you have finished entering data and now you need to check the input. For example by adding a test enter button or for example when an edit textbox loses focus.



0


source







All Articles