'TextWatcher class trims space from end when spacebar is pressed and cursor moves to beginning of editText

Below is my textWatcher class:

class MyTextWatcher(private val editText: EditText) : TextWatcher {
    override fun beforeTextChanged(
        s: CharSequence?,
        start: Int,
        count: Int,
        after: Int
    ) {
    }

    override fun onTextChanged(
        s: CharSequence?,
        start: Int,
        before: Int,
        count: Int
    ) {
        val text = editText.text.toString()
        if (text.startsWith(" ")) {
            editText.setText(text.trim())
        }
        else if (text.endsWith(" ")){
            editText.setText(text.trim())
        }
        else if (text == " "){
            editText.setText(text.trim())
        }
    }

    override fun afterTextChanged(s: Editable?) {}

}

After writing in editText field when i press spacebar in the end of word, editText cursor moves to the beginning of the editText field before 1st letter.

What should i do such that when i press spacebar cursor should remain at the same position it should not go at beginning?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source