Question

How to Place the Cursor at the End of an EditText in Android Java

kotlinjavaandroidandroid-edittextkeylistener

Question

I am updating the value of an EditText inside a key listener.

However, after I change the text programmatically, the cursor moves to the beginning of the EditText. I want the cursor to stay at the end of the text instead.

How can I move the cursor to the end of the text in an EditText?

editText.setText("Updated text");

Short Answer

By the end of this page, you will understand why an EditText cursor often jumps to the beginning after setText(), how cursor position works in Android, and how to place the cursor at the end using setSelection() safely.

Concept

When you change the text inside an Android EditText programmatically using setText(), Android replaces the current text content. As part of that update, the selection state—meaning the cursor position or highlighted range—can be reset.

That is why the cursor often moves to the start of the field after the text changes.

To control where the cursor appears, you use:

editText.setSelection(position);

If you want the cursor at the end, the position should usually be the length of the text:

editText.setSelection(editText.getText().length());

This matters in real apps because many inputs are formatted while the user types, such as:

  • phone numbers
  • currency values
  • credit card numbers
  • search boxes with auto-updates
  • forms that normalize text

Without restoring the cursor position, the typing experience feels broken because the user keeps getting sent back to the start of the input.

Mental Model

Think of an EditText like a text document with a blinking bookmark.

  • setText() replaces the document contents.
  • Replacing the contents may reset the bookmark.
  • setSelection() puts the bookmark back where you want it.

So if you replace the text and want typing to continue naturally, you must manually place the bookmark again—usually at the end.

Take Quiz

Syntax and Examples

The basic pattern is:

editText.setText("Hello world");
editText.setSelection(editText.getText().length());

Example: move cursor to the end

EditText editText = findViewById(R.id.editText);

editText.setText("Android");
editText.setSelection(editText.getText().length());

What this does

  • setText("Android") updates the field.
  • getText().length() gets the number of characters currently in the field.
  • setSelection(...) places the cursor at that index.

Shorter version when text is already set

editText.setSelection(editText.length());

This works because EditText inherits length-related behavior from TextView, and the current text length is used as the cursor position.

Example inside a listener

editText.setOnKeyListener((v, keyCode, event) -> {
    editText.setText("Updated text");
    editText.setSelection(editText.getText().length());
    return false;
});

If you are modifying user input frequently, a TextWatcher is often more appropriate than a key listener, but the cursor control idea is the same.

Step by Step Execution

Consider this code:

editText.setText("Hello");
editText.setSelection(editText.getText().length());

Step-by-step

  1. setText("Hello") replaces the current content of the EditText.
  2. The new text becomes Hello.
  3. The length of Hello is 5.
  4. setSelection(5) places the cursor at index 5.
  5. In a 5-character string, index 5 means after the last character.

So the visual result is:

Hello|

Where | represents the cursor.

Another example

editText.setText("abc123");
editText.setSelection(editText.getText().length());

Trace:

  • Text becomes abc123
  • Length is 6
  • Cursor moves to position 6

Result:

abc123|

Real World Use Cases

Placing the cursor correctly after text updates is common in Android apps.

Input formatting

A phone number field may change:

1234567890

into:

123-456-7890

After formatting, the cursor should remain in a sensible position, often at the end.

Auto-capitalization or normalization

An app may convert text like:

john doe

to:

John Doe

If the cursor jumps to the beginning, typing becomes frustrating.

Chat or note apps

Draft text may be restored or updated from saved state, and the app may want the cursor at the end so the user can continue typing.

Search fields

A search box might trim spaces or clean invalid characters as the user types. Resetting the cursor to the end keeps interaction smooth.

Take Quiz

Real Codebase Usage

In real Android projects, developers usually combine text updates with selection management.

Common pattern

String updated = "Updated text";
editText.setText(updated);
editText.setSelection(updated.length());

This is clean because the same string is used for both operations.

Guarding against invalid positions

If the text might be null or change unexpectedly, developers often check length before calling setSelection().

Editable text = editText.getText();
if (text != null) {
    editText.setSelection(text.length());
}

In formatting code

When building formatted input fields, developers often:

  • remove the listener temporarily
  • update the text
  • restore the cursor position
  • attach the listener again

This avoids infinite loops or repeated updates.

With validation

After fixing invalid input automatically, apps often move the cursor to the end so the user can continue typing naturally.

Early-return style

Editable text = editText.getText();
if (text == null) {
    return;
}
editText.setSelection(text.length());

This keeps the code safe and readable.

Common Mistakes

1. Calling setText() without restoring the cursor

Broken example:

editText.setText("Updated text");

Problem:

  • The cursor may move to the start.

Fix:

editText.setText("Updated text");
editText.setSelection(editText.getText().length());

2. Using an invalid selection index

Broken example:

editText.setSelection(100);

Problem:

  • If the text is shorter than 100 characters, Android can throw an error.

Fix:

int length = editText.getText().length();
editText.setSelection(length);

3. Setting selection before setting text

Broken example:

editText.setSelection(editText.getText().length());
editText.setText("New value");

Problem:

  • The selection is applied to the old text, then lost when the new text is set.

Fix:

editText.setText("New value");
editText.setSelection(editText.getText().length());

4. Causing repeated listener triggers

If you update text inside a TextWatcher, that update may trigger the watcher again.

Broken pattern:

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void afterTextChanged(Editable s) {
        editText.setText(s.toString().toUpperCase());
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}
});

Possible issue:

  • repeated updates
  • cursor jumps
  • poor typing experience

Fix:

Use a guard flag or temporarily remove the watcher before changing text.

Comparisons

ApproachWhat it doesWhen to useNotes
setText()Replaces the textWhen content must changeMay reset cursor position
setSelection(index)Moves the cursor or selectionAfter text is already setIndex must be valid
setSelection(length)Moves cursor to the endMost common solution hereBest for append-like behavior
append()Adds text to the endWhen you want to keep existing text and add moreOften naturally leaves cursor near the end

setText() vs append()

editText.setText("Hello");   // Replaces all text
editText.append(" world");   // Adds to existing text

Use setText() when replacing content. Use append() when adding content.

Key listener vs TextWatcher

OptionBest forLimitation
OnKeyListenerReacting to key eventsNot ideal for all text changes
TextWatcherReacting to text changesCan retrigger if you modify text inside it

If your goal is to react to changing text, TextWatcher is often the better tool.

Take Quiz

Cheat Sheet

// Put cursor at the end after changing text
editText.setText("Updated text");
editText.setSelection(editText.getText().length());

Quick rules

  • Call setSelection() after setText().
  • Use editText.getText().length() for the end position.
  • Do not use an index larger than the text length.
  • If updating text inside listeners, watch for repeated callbacks.

Useful snippets

editText.setSelection(editText.length());
String value = "Hello";
editText.setText(value);
editText.setSelection(value.length());
Editable text = editText.getText();
if (text != null) {
    editText.setSelection(text.length());
}

Edge case

If the field is empty:

editText.setText("");
editText.setSelection(0);

That is still valid because the end of an empty string is position 0.

FAQ

How do I move the cursor to the end of an EditText in Android?

Use setSelection() with the current text length:

editText.setSelection(editText.getText().length());

Why does the cursor move to the beginning after setText()?

Because setText() replaces the text content, and Android may reset the selection state during that update.

Should I call setSelection() before or after setText()?

Always after setText(). Otherwise, the new text update can override the cursor position.

Can setSelection() cause an error?

Yes. If you pass an index larger than the text length, it can throw an exception.

Is OnKeyListener the best place to modify EditText content?

Not always. For text changes, TextWatcher is usually more reliable because not all text changes come from key presses.

Can I place the cursor somewhere other than the end?

Yes. Pass any valid character index:

editText.setSelection(2);

What if I want to select text instead of just moving the cursor?

You can use the two-argument version of setSelection(start, end) to highlight a range.

Take Quiz

Mini Project

Description

Build a simple Android input formatter that converts entered text to uppercase and keeps the cursor at the end after every programmatic update. This demonstrates the practical use of setText() together with setSelection() in a realistic typing scenario.

Goal

Create an EditText that automatically formats user input and keeps typing smooth by placing the cursor at the end after each update.

Requirements

  • Create an Android screen with one EditText.
  • Listen for text changes.
  • Convert the entered text to uppercase.
  • Prevent infinite update loops while changing text programmatically.
  • After updating the text, place the cursor at the end.
Take Quiz

Keep learning

Related questions

View more