Home > Net >  How to insert a space every 2 digits when inputting a string in edittext in Android?
How to insert a space every 2 digits when inputting a string in edittext in Android?

Time:12-16

I want to insert a space every 2 digits when inputting a string in edittext

For example, if you have the string 'abcdefghijk'

I want the edittext to come out like this 'ab cd ef gh ij k'

What should I do? thank you

CodePudding user response:

The best way of doing this is to do something similar that this answer is doing.

For your code it would mean something like this:

class SpacedTextWatcher(private val editText: EditText) : TextWatcher {

    override fun afterTextChanged(s: Editable?) {
        editText.removeTextChangedListener(this)
        val initialLength = editText.text.length

        val v = s.toString().chunked(2).joinToString(" ")

        val cp = editText.selectionStart
        editText.setText(v)
        val endLength = editText.length()
        val selection = (cp   (endLength - initialLength))
        if (selection > 0 && selection <= editText.text.length) {
            editText.setSelection(selection)
        } else {
            editText.setSelection(editText.text.length - 1)
        }


        editText.addTextChangedListener(this)
    }

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

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

This answer is not handling special use-cases where there is a space in the string or anything else, but I think you can figure out the rest yourself. Just make sure you register this textWatcher on the editText you want to format.

CodePudding user response:

Here is the exact solution what you want:

 fun editTextSetContentMemorizeSelection(editText: EditText, charSequence: CharSequence) {
        var selectionStart = editText.selectionStart
        var selectionEnd = editText.selectionEnd
        editText.setText(charSequence.toString())
        if (selectionStart > charSequence.toString().length) {
            selectionStart = charSequence.toString().length
        }
        if (selectionStart < 0) {
            selectionStart = 0
        }
        if (selectionEnd > charSequence.toString().length) {
            selectionEnd = charSequence.toString().length
        }
        if (selectionEnd < 0) {
            selectionEnd = 0
        }
        editText.setSelection(selectionStart, selectionEnd)
    }
    
    fun formatStrWithSpaces(can: CharSequence): String? {
        val sb = StringBuffer()
        for (i in 0 until can.length) {
            if (i != 0 && i % 2 == 0) {
                sb.append(' ')
            }
            sb.append(can[i])
        }
        return sb.toString()
    }

In your onCreate or where ever you want to use textwatcher:

editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        val origin = s.toString().replace(" ".toRegex(), "")
        val formatStr = formatStrWithSpaces(origin)
        if (s.toString() != formatStr) {
            editTextSetContentMemorizeSelection( editText, formatStr!!)
            if (before == 0 && count == 1 && formatStr!![ editText.getSelectionEnd() - 1] == ' ') {
                editText.setSelection(editText.getSelectionEnd()   1)
            }
        }
    }

    override fun afterTextChanged(s: Editable) {}
})

Here is the Source of this answer. You can also check.

  • Related