What's the best way to limit text length of EditText in Android
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
The best way to limit the length of an EditText in Android is usually not a custom TextWatcher. The normal solution is an InputFilter.LengthFilter, because it enforces the limit at the input layer instead of letting the user enter extra text and trimming it afterward.
The Simple XML Option
If the limit is static, the easiest approach is the XML attribute.
This is concise, declarative, and easy to understand in layout code.
The Programmatic Option
If the limit must be set dynamically, use an input filter programmatically.
This is the preferred runtime approach because it behaves the same way as the XML limit and still works at the input-filter level.
Why TextWatcher Is Usually Not the Best Tool
A TextWatcher can observe text changes, but using it to cut text back after the user types too much is usually clumsier.
This can work, but it is more fragile. Cursor position, recursion concerns, and user experience all become harder to manage than with a proper input filter.
TextWatcher is better for reacting to input, not for basic length enforcement.
When a Custom Filter Makes Sense
If the rule is more complicated than a simple maximum length, write a custom InputFilter. For example, you may want a limit that depends on the type of characters being entered.
That is more powerful than maxLength, but you should only go there when a simple length filter is not enough.
In other words, start with the built-in filter and only move to custom logic when the requirement is genuinely more than “cap the number of characters.” That keeps the input stack predictable and avoids surprising editing behavior.
It also reduces the amount of code you need to maintain around basic text entry.
Common Pitfalls
- Using
TextWatcherfor basic length limiting when an input filter is simpler and more robust. - Forgetting that XML
android:maxLengthalready solves many static cases. - Truncating text after the fact and creating a jarring cursor or editing experience.
- Writing a custom filter when a standard
LengthFilteralready handles the requirement. - Treating validation and input filtering as the same thing when they serve different roles.
Summary
- Use
android:maxLengthin XML for simple static limits. - Use
InputFilter.LengthFilterfor dynamic runtime limits. - Prefer input filters over
TextWatcherfor basic length enforcement. - Reach for custom filters only when the rule is more complex than a fixed maximum.
- The best solution is the one that blocks invalid input cleanly instead of repairing it later.

