Question
How to Place the Cursor at the End of an EditText in Android Java
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.
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 ;
});
Step by Step Execution
Consider this code:
editText.setText("Hello");
editText.setSelection(editText.getText().length());
Step-by-step
setText("Hello")replaces the current content of theEditText.- The new text becomes
Hello. - The length of
Hellois5. setSelection(5)places the cursor at index5.- In a 5-character string, index
5means 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
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.
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();
(text == ) {
;
}
editText.setSelection(text.length());
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.
Comparisons
| Approach | What it does | When to use | Notes |
|---|---|---|---|
setText() | Replaces the text | When content must change | May reset cursor position |
setSelection(index) | Moves the cursor or selection | After text is already set | Index must be valid |
setSelection(length) | Moves cursor to the end | Most common solution here | Best for append-like behavior |
append() | Adds text to the end | When you want to keep existing text and add more | Often naturally leaves cursor near the end |
setText() vs append()
Cheat Sheet
// Put cursor at the end after changing text
editText.setText("Updated text");
editText.setSelection(editText.getText().length());
Quick rules
- Call
setSelection()aftersetText(). - 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);
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();
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.
Keep learning
Related questions
Android AlarmManager Example: Scheduling Tasks with AlarmManager
Learn how to use Android AlarmManager to schedule tasks, set alarms, and handle broadcasts with a simple beginner example.
Can You Extend a Data Class in Kotlin? Inheritance, Limits, and Better Alternatives
Learn why Kotlin data classes cannot be extended, what causes the component function clash, and which alternatives to use instead.
Difference Between List and Array in Kotlin
Learn the difference between List and Array in Kotlin, including mutability, size, APIs, performance, and when to use each one.