Tuesday 6 February 2018

Android EditText : Input Filter with Restrictions

Note : This post is not about InputFilter but about Restriction Filter for an Android EditText.
If visited page by mistake, one could follow Ctrl+W (on Firefox).


InputFilter interface's following method is origin of all such rules.

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend){
  // Governs what to input and what not to
}

So first let's get to know some use cases of InputFilter before we actually show how we created a restriction filter out of it.

InputFilter is very easy in cases where we have to use it to
1. restrict characters from input at certain positions.
2. restrict characters from deletion from certain positions.

Above cases can be easily handled by checking only three parameters of the  interface's implemented filter() method as :
1. source -> input content going to be added .
2. dstart -> starting position where it is to be placed.
3. dend -> ending position where it is to be placed.


Please follow this simple example demoing a non-editable country code for PhoneNumber EditText  (Note : World knows about TextWatcher as well :))


class CountryCodeInputFilter implements InputFilter {
        
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            //Back Key Press conditions
            boolean deleteCond0 = dstart == 0 && dend == 1; // +
            boolean deleteCond1 = dstart == 1 && dend == 2; // 9
            boolean deleteCond2 = dstart == 2 && dend == 3; // 5

            boolean insertCond0 = dstart == 0 && dend == 0; // ahead of +
            boolean insertCond1 = dstart == 1 && dend == 1; // ahead of 9
            boolean insertCond2 = dstart == 2 && dend == 2; // ahead of 5

            // Handling Back Key Presses
            if ((deleteCond0 || deleteCond1 || deleteCond2) && (source.equals(""))) {
                // BackPress
                if (deleteCond0) {
                    return "+";
                } else if (deleteCond1) {
                    return "9";
                } else {
                    return "5";
                }
            }

            // Handling insertions at invalid positions
            if ((insertCond0 || insertCond1 || insertCond2) && (!source.equals(""))) {
                return "";
            }

            return null;
        }
}

Got updates ?
Welcome.


No comments:

Post a Comment