简体   繁体   中英

How can I add space after 4 character in EditText at Kotlin?

I'm try to make EditText for bank cards. I need to add space after every 4 number. I already tried another answers at stackoverflow but non of them working for me. I try to make it from count (I use textwatcher) but I can't do it. Other answers use insert method for add space but insert method isn't available. When I write insert it become red so I want to ask for learn. How can I make it?

I tried something but I really not know what I'm doing. I really need advices.

Here my editText textwatcher code:

private val textWatcher = object : TextWatcher {

    override fun afterTextChanged(s: Editable?) {

    }
    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {


        var txt = s.toString()

        println(txt)
        println(s!!.length)
        if (s!!.length%4 == 0){
            txt = txt + " "
            println(txt)
        }



    }
}

You are creating a text variable not seting the text to the EditText view

txt = txt + " "

You could think that is modifying the text, but primitives and String are immutable so that is another reference in memory, so even if you are trying to us mutability to achieve it won't work.

if (s!!.length%4 == 0){
    txt = txt + " "
    yourEditText.setText(txt)
}

With EditText you have to use the setter because the field assigned to the text is an Editable so the setText method wraps the conversion from String to Editable

There is a common warning regarding this, if I don't miss remember is also on the docs, modifying during a TextWatcher callback can trigger an infinite loop, in this case, it won't because the change to the text will be " filtered " by the condition.

Just use myedittext.append("") like this

if (s...length%4 == 0){ yourEditText.append(" ") }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM