android
text change listener
android development
edittext
user input handling

android on Text Change Listener

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Android's TextWatcher interface lets developers respond to text changes in EditText fields in real time. This is essential for features like search-as-you-type, input validation, character counters, and dynamic UI updates. This article explains how to implement TextWatcher, demonstrates practical examples in both Java and Kotlin, and covers best practices for avoiding common issues.

The TextWatcher Interface

The TextWatcher interface provides three callback methods that fire at different stages of a text modification:

  • beforeTextChanged(CharSequence s, int start, int count, int after): Called before the text is modified. The parameters tell you what the current text is, where the change starts, how many characters will be removed, and how many will be added.
  • onTextChanged(CharSequence s, int start, int before, int count): Called during the change. The s parameter contains the new text, start is where the change begins, before is how many old characters were replaced, and count is how many new characters were inserted.
  • afterTextChanged(Editable s): Called after the change is complete. The Editable parameter lets you modify the text further, which is useful for formatting or validation.

Basic Implementation in Java

java
1EditText editText = findViewById(R.id.search_input);
2
3editText.addTextChangedListener(new TextWatcher() {
4    @Override
5    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
6        // Save state before the change if needed
7    }
8
9    @Override
10    public void onTextChanged(CharSequence s, int start, int before, int count) {
11        // React to the change in progress
12        Log.d("TextWatch", "Current text: " + s.toString());
13    }
14
15    @Override
16    public void afterTextChanged(Editable s) {
17        // Perform validation or trigger search
18        String input = s.toString().trim();
19        if (input.length() >= 3) {
20            performSearch(input);
21        }
22    }
23});

Kotlin Implementation with Extension Function

Kotlin makes TextWatcher more concise. You can create an extension function that only requires the callback you care about:

kotlin
1fun EditText.afterTextChanged(action: (String) -> Unit) {
2    addTextChangedListener(object : TextWatcher {
3        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
4        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
5        override fun afterTextChanged(s: Editable?) {
6            action(s?.toString().orEmpty())
7        }
8    })
9}
10
11// Usage
12val searchInput = findViewById<EditText>(R.id.search_input)
13searchInput.afterTextChanged { text ->
14    if (text.length >= 3) {
15        viewModel.search(text)
16    }
17}

Practical Example: Input Validation with Error Display

A common use case is validating email input and showing an error message in real time:

kotlin
1val emailInput = findViewById<EditText>(R.id.email_input)
2val emailLayout = findViewById<TextInputLayout>(R.id.email_layout)
3
4emailInput.afterTextChanged { text ->
5    emailLayout.error = when {
6        text.isEmpty() -> null
7        !Patterns.EMAIL_ADDRESS.matcher(text).matches() -> "Invalid email address"
8        else -> null
9    }
10}

Firing a network request on every keystroke wastes resources. Use a Handler to debounce the input so the search only triggers after the user stops typing for a short period:

kotlin
1val handler = Handler(Looper.getMainLooper())
2var searchRunnable: Runnable? = null
3
4searchInput.afterTextChanged { text ->
5    searchRunnable?.let { handler.removeCallbacks(it) }
6
7    if (text.length >= 3) {
8        searchRunnable = Runnable { viewModel.search(text) }
9        handler.postDelayed(searchRunnable!!, 300)
10    }
11}

This waits 300 milliseconds after the last keystroke before executing the search. Each new keystroke cancels the previous pending search.

Practical Example: Character Counter

kotlin
1val messageInput = findViewById<EditText>(R.id.message_input)
2val charCounter = findViewById<TextView>(R.id.char_counter)
3val maxChars = 280
4
5messageInput.addTextChangedListener(object : TextWatcher {
6    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
7    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
8    override fun afterTextChanged(s: Editable?) {
9        val remaining = maxChars - (s?.length ?: 0)
10        charCounter.text = "$remaining characters remaining"
11        charCounter.setTextColor(
12            if (remaining < 0) Color.RED else Color.GRAY
13        )
14    }
15})

Common Pitfalls

Infinite loop from modifying text in afterTextChanged. If you change the Editable inside afterTextChanged, the TextWatcher fires again. Guard against this with a flag:

kotlin
1var isUpdating = false
2
3editText.addTextChangedListener(object : TextWatcher {
4    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
5    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
6    override fun afterTextChanged(s: Editable?) {
7        if (isUpdating) return
8        isUpdating = true
9        s?.replace(0, s.length, s.toString().uppercase())
10        isUpdating = false
11    }
12})

Memory leaks from not removing the listener. In Fragment-based architectures, add the listener in onViewCreated and consider nullifying references in onDestroyView. If you hold a reference to the TextWatcher instance, you can call removeTextChangedListener() during cleanup.

Performing heavy work on the main thread. Network calls, database queries, and complex computations inside onTextChanged or afterTextChanged will freeze the UI. Always offload heavy work to a coroutine or background thread, and use debouncing to limit invocation frequency.

Using onTextChanged instead of afterTextChanged for validation. The onTextChanged method fires before the Editable is finalized. If you read the text at that point, cursor positioning and formatting may not be complete. Prefer afterTextChanged for any logic that depends on the final state of the input.

Summary

The TextWatcher interface is the standard way to observe text changes in Android EditText fields. Implement afterTextChanged for validation and search triggers, use debouncing to limit network calls, and guard against infinite loops when modifying text inside the callback. Kotlin extension functions simplify the boilerplate significantly. Always remove listeners when the view is destroyed to prevent memory leaks.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms