Question

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

javaandroidkotlinandroid-edittextkeylistener

Question

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

However, when 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("New value");

Short Answer

By the end of this page, you will understand why the cursor position changes when you call setText() on an Android EditText, how to place the cursor at the end using setSelection(), and how this pattern is used safely in real Android apps.

Concept

When you update the text inside an Android EditText using setText(), Android replaces the current text content. During that process, the selection state, including the cursor position, may be reset.

If you want the cursor to appear at a specific position after changing the text, you must explicitly set the selection again.

The most common solution is:

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

This places the cursor at the end of the current text.

Why this matters:

  • Users expect text fields to behave naturally while typing.
  • Programmatically changing text is common in formatting, validation, autocomplete, and input cleanup.
  • If the cursor jumps to the wrong place, typing becomes frustrating.

In Android, cursor placement is controlled through the text selection API. For an EditText, a single cursor position is just a selection where the start and end are the same index.

Mental Model

Think of an EditText like a sentence written on paper with a finger marking the current typing position.

  • setText() replaces the sentence.
  • When the sentence is replaced, your finger loses its old position.
  • setSelection(position) puts your finger back where you want it.

So if you want typing to continue at the end, you must move the finger to the last character after replacing the text.

Take Quiz

Syntax and Examples

The core pattern is:

editText.setText("Hello");
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());

After this runs:

  • The text becomes Android
  • The cursor is placed after the last character

Example: Inside a listener

editText.setOnKeyListener((v, keyCode, event) -> {
    String updatedText = editText.getText().toString().trim();
    editText.setText(updatedText);
    editText.setSelection(editText.getText().length());
    return false;
});

This updates the text and then immediately moves the cursor to the end.

Example: Reusing the current string

String value = editText.getText().toString();
String newValue = value + "!";

editText.setText(newValue);
editText.setSelection(newValue.length());

Using newValue.length() is also valid because it matches the text that was just set.

Step by Step Execution

Consider this example:

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

Step by step:

  1. setText("Hello World") replaces the current text in the EditText.
  2. Android updates the internal editable content.
  3. The previous cursor position is no longer guaranteed.
  4. editText.getText().length() returns 11.
  5. setSelection(11) moves the cursor to index 11.
  6. In a string of length 11, index 11 means the cursor is placed after the last character.

Small trace

Text: Hello World

Character positions:

  • H at index 0
  • e at index 1
  • ...
  • d at index 10
  • end position at index 11

So this line:

editText.setSelection(11);

means: place the cursor at the end, ready for more typing.

Real World Use Cases

This pattern is useful in many Android input scenarios:

  • Phone number formatting: add spaces or dashes while the user types.
  • Uppercase/lowercase normalization: update text formatting without leaving the cursor in the wrong place.
  • Appending generated text: add a suffix, prefix, or token and keep typing at the end.
  • Search boxes: restore text after filtering or sanitizing input.
  • Form cleanup: trim accidental spaces and keep the user experience smooth.
  • Chat or note apps: insert mentions, tags, or templated text.

Example:

String cleaned = editText.getText().toString().replace("  ", " ");
editText.setText(cleaned);
editText.setSelection(editText.getText().length());

This keeps the cursor at the end after cleaning up extra spaces.

Take Quiz

Real Codebase Usage

In real Android projects, developers often combine setText() and setSelection() with patterns that make text handling safer.

Common patterns

  • Input normalization: clean or format text after input.
  • Guard clauses: avoid resetting text if nothing actually changed.
  • Validation: update the field only when the new value is valid.
  • Error handling: ensure the selection index is within bounds.

Example: Guard clause to avoid unnecessary updates

String current = editText.getText().toString();
String formatted = current.trim();

if (!current.equals(formatted)) {
    editText.setText(formatted);
    editText.setSelection(formatted.length());
}

This avoids extra updates when the text is already correct.

Example: Safe selection after dynamic updates

String result = "User: " + input;
editText.setText(result);
editText.setSelection(result.length());

Important note

If you change text inside listeners such as TextWatcher, be careful not to create loops where updating the text triggers the same listener again. In real codebases, developers often remove the watcher temporarily or use flags to prevent repeated updates.

Common Mistakes

1. Calling setText() without restoring the cursor

Broken example:

editText.setText("Updated");

Problem:

  • The cursor may move to the start or another unexpected position.

Fix:

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

2. Using an invalid selection index

Broken example:

editText.setText("Hi");
editText.setSelection(10);

Problem:

  • The text length is only 2
  • This can cause an exception

Fix:

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

3. Getting the length before changing the text

Broken example:

int oldLength = editText.getText().length();
editText.setText("A much longer value");
editText.setSelection(oldLength);

Problem:

  • The old cursor position may not match the new text

Fix:

editText.setText("A much longer value");
editText.setSelection(editText.getText().length());

4. Updating text repeatedly inside listeners

Broken example:

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

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

Problem:

  • Changing the text can trigger the watcher again
  • This may cause loops or jumpy behavior

Fix:

  • Use a guard flag
  • Only update when the value is actually different
  • Restore the cursor after the update

Comparisons

ApproachWhat it doesWhen to use it
setText()Replaces the textUse when you want to update the field content
setSelection(index)Moves the cursor to a specific positionUse after changing text or to control cursor placement
append()Adds text to the endUseful when you only need to add text without replacing everything

setText() vs append()

editText.setText("Hello");
editText.append(" World");
  • setText() replaces everything
  • append() keeps existing text and adds more at the end

If your goal is simply to add text at the end, append() may naturally keep the cursor near the end. But if you must replace the full value, use setText() followed by setSelection().

setSelection() with one index vs two indexes

editText.setSelection(5);
  • Places a single cursor at position 5
editText.setSelection(2, 5);
  • Selects a text range from 2 to 5

For this question, the one-argument version is the right choice.

Take Quiz

Cheat Sheet

// Replace text and move cursor to end
editText.setText("New value");
editText.setSelection(editText.getText().length());

Rules

  • Call setSelection() after setText()
  • Use a valid index from 0 to text.length()
  • To place the cursor at the end, use text.length()

Quick examples

String value = "Hello";
editText.setText(value);
editText.setSelection(value.length());
editText.append("!");
editText.setSelection(editText.getText().length());

Edge cases

  • Empty string:
editText.setText("");
editText.setSelection(0);
  • Invalid selection index can throw an error
  • Reformatting text inside listeners may cause repeated callbacks

Best practice

String formatted = getFormattedValue();
if (!formatted.equals(editText.getText().toString())) {
    editText.setText(formatted);
    editText.setSelection(formatted.length());
}

FAQ

How do I place the cursor at the end of an EditText in Android?

Use setSelection() after setText():

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

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

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

Can I move the cursor to a specific position instead of the end?

Yes. Pass the exact index you want:

editText.setSelection(3);

What is the difference between setSelection(length) and append()?

append() adds text to the end. setSelection(length) explicitly places the cursor at the end. You often use setSelection(length) after setText().

Can setSelection() cause an error?

Yes. If you pass an index smaller than 0 or larger than the text length, it can fail.

Should I use this inside a TextWatcher or KeyListener?

Yes, but carefully. If your code updates the text repeatedly inside a listener, you may trigger extra callbacks or create loops.

What if the EditText is empty?

Use index 0:

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

Mini Project

Description

Build a small Android screen with an EditText and a button that formats the typed text by trimming extra spaces and converting it to uppercase. After formatting, the cursor should be placed at the end of the text so the user can continue typing naturally.

Goal

Create an EditText formatter that updates text programmatically and keeps the cursor at the end.

Requirements

[ "Create an EditText for user input.", "Add a button that formats the current text.", "Trim leading and trailing spaces from the text.", "Convert the text to uppercase.", "After updating the EditText, move the cursor to the end." ]

Take Quiz

Keep learning

Related questions

View more