Skip to content Skip to sidebar Skip to footer

When My Inputfilter Source Comes In As Spannable, The Source Does Not Remove The Characters I Filter Out

I am filtering most characters and numbers out in this use case. When I type several 'filtered' characters, let's say 555, the source of each following filter event still has those

Solution 1:

I suggest this to concisely take the source delimiters into account:

overridefunfilter(source: CharSequence, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
    val builder = StringBuilder()
    for (c in source.subSequence(start, end) {
        if (c.isValid()) builder.append(c)
    }
    returnif (builder.length == end - start) {
        null
    } else {
        showInputToast(R.string.textInputInvalid)
        //...
    }
}

Solution 2:

You might consider simplifying the whole thing to reject any incoming block of text if it contains any invalid characters. Presumably, you will get either one new character at a time, or the user is pasting a block of text. Do you really want to filter pieces of a block of text that contains invalid characters? In many cases, this would be unexpected behavior.

So if it's acceptable behavior to do this, your filter simplifies down to:

overridefunfilter(source: CharSequence, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
    for (i in start until end) {
        if (!source.charAt(i).isValid()) {
            showInputToast(R.string.textInputInvalid)
            return""
        }
    }
    returnnull
}

Post a Comment for "When My Inputfilter Source Comes In As Spannable, The Source Does Not Remove The Characters I Filter Out"