In this article, we will see how to programmatically move the cursor to the end of the text in EditText.

By default, when the EditText receives focus, the cursor appears at the beginning of the text. For a better user experience, it is always important to position the cursor at the end of the text automatically.

Using setSelection()

We can use the setSelection() API to move the cursor to the end of the text in an EditText programmatically. This method allows us to set the position of the cursor within the EditText.

Example:

Let us see an example where we have an editText and we want to move the cursor to the end automatically went the EditText gains focus.

import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var editText: EditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        editText = findViewById(R.id.editText)

        editText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                editText.setSelection(editText.text.length)
            }
        }
    }
}

In the above example, we have an EditText field with the ID editText in our XML layout. In the onCreate() method, we get the EditText using findViewByID(). We also set an OnFocusChangeListener on the EditText to listen for focus changes

When the EditText gains focus (hasFocus is true), we call setSelection() on the EditText and pass the length of the text as the argument. This sets the cursor position to the end of the text.

Categorized in:

Tagged in:

,