Search code examples
javaandroidandroid-edittextandroid-textinputlayout

Remove whitespace before Paste with a Max Length


So I use TextInputEditText with a max length of 8 .

If I paste "1234 1234", it will become "1234 123". My goal is for it to become "12341234"

The hard part is the max length, because if I use the usual filter or onTextChange, it won't work due to the length cutted first before it trim whitespace. It will become "1234123" instead.

So I want to trim the whitespace before it pasted to the edit text.

Any idea ?

Edit : Because every commenter never read my question. Here's why onTextChanged dont work on mine. I copy "1234 1234". When I pasted, due to max length it will be converted to "1234 123". Then go to TextWatcher Listener, or RxJava Listener. So if I put it in onTextChange,beforeTextChange,or afterTextChange, it already become "1234 123", hence I can't achieve the goal of "12341234"


Solution

  • Here is an InputFilter.LengthFilter that should work:

    private class MyLengthFilter(max: Int) : InputFilter.LengthFilter(max) {
        private val mMax = max
    
        override fun filter(
            source: CharSequence, start: Int, end: Int, dest: Spanned, dstart: Int, dend: Int
        ): CharSequence? {
            val newSource = super.filter(source, start, end, dest, dstart, dend)
    
            if (newSource.isNullOrEmpty()) return newSource
    
            // Calculate how many characters were truncated
            val truncated = (end - start) - newSource.length
            if (truncated <= 0) return newSource
    
            // Remove all space characters. Adjust this to change how the replacement string is adjusted.
            val noSpaceSource = source.filter { !Character.isSpaceChar(it) }
            if (noSpaceSource == source) return newSource // No white space.
    
            return super.filter(
                noSpaceSource, start, start + noSpaceSource.length, dest, dstart, dend
            ) ?: noSpaceSource
        }
    }
    

    Take note of the comment in InputFilter regarding spans when source is an instance of Spanned or Spannable in case it effects you.