Explain Codes LogoExplain Codes Logo

Place cursor at the end of text in EditText

kotlin
cursor-positioning
edittext
kotlin-extension-functions
Anton ShumikhinbyAnton Shumikhin·Sep 20, 2024
TLDR

Call the setSelection() method on your EditText instance, using the length() of the current text (getText()) as the parameter:

editText.setText("Your text"); editText.setSelection(editText.getText().length()); // 'Your text'. Who's there? The end!

The cursor swiftly leaps to the end of the text.

Kotlin's touch

Brevity is a virtue, and Kotlin knows it well. Set the cursor at the end with a sleeker line of code:

editText.setText("Your text"); editText.setSelection(editText.length()); // Swift as a coursing river!

You're not limited to the end. Command the cursor to a specific location by replacing length() with any valid index.

Deeper understanding of cursor placement

Correct cursor placement is vital for a seamless user experience. Let's uncover additional methods and techniques to ace it.

Changes in text programmatically

Code often modifies EditText content. To maintain the cursor at the end following such updates, enlist append():

editText.append(" and more text"); // "Your text and more text". And, it's done!

The append() method adds text and abides by the cursor's destiny – moving to the end.

Tackling delayed layouts

When layout delays brush off your cursor positioning, do a judo flip with Runnable to queue the instruction:

editText.post(() -> editText.setSelection(editText.getText().length())); // Patience is golden!

Even when the layout lags, the cursor lands correctly.

Kotlin extension function

Exploit Kotlin's extension functions to streamline your code:

fun EditText.placeCursorToEnd() { this.setSelection(this.text.length) } // Usage: editText.placeCursorToEnd() // Cursors love short trips!

This handy snippet moves the cursor to the far end effortlessly.

Cursor movement flexibility

There are situations where you need the cursor to commence at the beginning of the EditText:

editText.setSelection(0); // Back to square one!

In case you need the cursor at a specific spot, entrust setSelection()

int position = 5; // Set the desired index editText.setSelection(position); // 5th time's the charm!

Crucial tips

While managing cursor positions, bear in mind

  • User interaction: Cursor location can change as the user intervenes with the EditText.
  • Text length: The desired index should always be within text boundseditText.getText().length().
  • Thread safety: Cursor placement code must run on the UI thread.