Monday, 1 February 2016

HB Blog 103: Using InputFilter To Restrict Android Mobile User's From Typing Wrong Input's.

             In Android development, we need very specific inputs from the users. Now a days, developer are trying to work n custom keyboard applications where user can type with more accuracy and correctly. Developer's come across a scenario where he has to restrict the charters to 0-9, a-z, A-Z and space-bar only specifically.
For example, user needs to enter his mobile number as an input in EditText. So, the developer should not allow Alphabets and special characters as an input. You can always declare the input method by adding the android:inputType attribute to the <EditText> element. But, imagine a case where we have to specify a range of digits such as in case of months. We have 12 months so we can have a EditText where input are supposed to be in a range from 1 to 12.

Usually, we apply if condition as below,

1
2
if(strMonth>=1 && strMonth<=12){
}

That's perfect, nothing wrong with this. But, 'Precaution is better than cure'. In above example, we can check this conditions after user makes mistake. Now, we can have more optimized solution to it. We can restrict user's from typing wrong input's itself using InputFilter. InputFilters can be attached to Editable's to constrain the change's that can be made to them.

We can do something like below code snippets,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 EditText et=(EditText)findViewById(R.id.btn);
        et.setFilters(new InputFilter[]{ new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int den) {
                try {
                    int input = Integer.parseInt(dest.toString() + source.toString());
                    if (isInRange(1, 12, input))
                        return null;
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                return "";
            }
        }});

Where isInRange() method is as below,

1
2
3
  private boolean isInRange(int min, int max, int input) {
        return max > min ? input >= min && input <= max : input >= max && input <= min;
    }

And, dont forget to add input type as android:inputType="number" in above case.

The filter method is called when the buffer is going to replace the range dstart dend of dest with the new text from the range start end of source. It returns the CharSequence that you would like to have placed there instead, including an empty string if appropriate, or null to accept the original replacement. Be careful to not to reject 0-length replacements, as this is what happens when you delete text.

No comments:

Post a Comment