The input filter is not working the same for all the keyboard

561 views Asked by At

I want to create an input filter for adding a vehicle number. I want to achieve this Video Demo, but my code is not working the same for all the keyboards. The "source" variable value from the below code is not the same for all the keyboards.

EDIT:

For Example, Let's assume the user wants to enter "MH 19". If a user press "1" then in "Google Keyboard" the value of a "source" variable is showing "1", but in "SwiftKey Keyboard" the value of a "source" variable is showing "MH1".

SpacesInputFilter.java

    public class SpacesInputFilter implements InputFilter {

    private final int max;
    private final int[] spaces;
    private final char space;

    public SpacesInputFilter(int max, int[] spaces, char space) {
        this.max = max;
        this.spaces = spaces;
        this.space = space;
    }

    @Override
    public CharSequence filter(CharSequence source,
                               int start,
                               int end,
                               Spanned dest,
                               int dstart,
                               int dend) {
        if (dest != null && dest.toString().trim().length() > max) {
            return null;
        }
        if (source.length() == 1 && contains(dstart, spaces) && source.charAt(0) != space) {
            return space + source.toString();
        }

        // handle copy-paste case
        int spacesCount = 0;
        if (start == 0 && source.length() == end) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < source.length(); i++) {
                char symbol = source.charAt(i);
                if (contains(i + spacesCount, spaces) && symbol != space) {
                    spacesCount++;
                    sb.append(space);
                }
                sb.append(symbol);
            }
            return sb.toString();
        }
        //unhandled: partial copy-paste
        return null; // keep original
    }

    private boolean contains(int i, int[] array) {
        for (int j: array) {
            if (j == i) {
                return true;
            }
        }
        return false;
    }
}

MainActivity.java

 edtVehicleNumber.setFilters(new InputFilter[] {
            new InputFilter.LengthFilter(13),
            new SpacesInputFilter(13, new int[]{2, 5, 8}, ' '),
    });
1

There are 1 answers

0
Parag Rane On

I have resolved the issue. Actually the problem was, software keyboards do some activities on its own while user types. These activities are intended to improve the experience. We need to somehow disable these activities so that we get the raw input.

So this worked for me,

        editText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);