Question
How to Place the Cursor at the End of an EditText in Android
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.
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());
Step by Step Execution
Consider this example:
editText.setText("Hello World");
editText.setSelection(editText.getText().length());
Step by step:
setText("Hello World")replaces the current text in theEditText.- Android updates the internal editable content.
- The previous cursor position is no longer guaranteed.
editText.getText().length()returns11.setSelection(11)moves the cursor to index11.- In a string of length
11, index11means the cursor is placed after the last character.
Small trace
Text: Hello World
Character positions:
Hat index0eat index1- ...
dat index10
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.
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);
Comparisons
| Approach | What it does | When to use it |
|---|---|---|
setText() | Replaces the text | Use when you want to update the field content |
setSelection(index) | Moves the cursor to a specific position | Use after changing text or to control cursor placement |
append() | Adds text to the end | Useful when you only need to add text without replacing everything |
setText() vs append()
editText.setText("Hello");
editText.append(" World");
setText()replaces everythingappend()keeps existing text and adds more at the end
If your goal is simply to add text at the end, may naturally keep the cursor near the end. But if you must replace the full value, use followed by .
Cheat Sheet
// Replace text and move cursor to end
editText.setText("New value");
editText.setSelection(editText.getText().length());
Rules
- Call
setSelection()aftersetText() - Use a valid index from
0totext.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
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.
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." ]
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.