Android Kotlin: How to implement text changed listener for an EditText

This code demonstrates how to implement a text changed listener for an EditText in an Android application written in Kotlin.

The code consists of two parts:

  1. MainActivity.kt: This file defines the main activity of the application. It handles the following functionalities:

    • Initializes the UI elements (EditText and TextView) by referencing them from the layout file.
    • Defines a list of color names.
    • Sets up the initial content of the TextView to display the list of colors.
    • Implements a text changed listener for the EditText. This listener is triggered whenever the text inside the EditText is changed.
    • Filters the color list based on the user's input in the EditText and displays the filtered list in the TextView.
  2. activity_main.xml: This file defines the layout of the activity. It includes two UI elements:

    • An EditText where the user can enter text.
    • A TextView that displays the list of colors and the filtered results.

Summary

This code snippet showcases a practical use case for text changed listeners in Android. By implementing this listener on an EditText, the application can dynamically react to user input and update the UI accordingly. In this example, the user can filter a list of colors based on what they type in the EditText, providing a real-time search experience.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView


class MainActivity : Activity() {
    private lateinit var editText:EditText
    private lateinit var textView:TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // get the widgets reference from XML layout
        editText = findViewById(R.id.editText)
        textView = findViewById(R.id.textView)

        // list of colors
        val colors = listOf(
            "Brick red", "African violet","Baby pink",
            "Cameo pink","Barbie Pink","Canary yellow",
            "Brilliant rose","Candy pink","Bright green",
            "Almond","Eton blue","Cornell red"
        )

        // show all of the colors on text view
        textView.text = "List of colors"
        colors.forEach { textView.append("\n$it") }


        // add text changed listener for edit text
        editText.addTextChangedListener(object: TextWatcher {
            // text watcher methods will be called when the text is changed
            override fun beforeTextChanged(p0: CharSequence?,
                                           p1: Int, p2: Int, p3: Int) {
                // do something before text changed
            }

            override fun onTextChanged(p0: CharSequence?,
                                       p1: Int, p2: Int, p3: Int) {
                // do something on text changed
                textView.text = "List filtered, on text changed\n"

                // filter the color list based on edit text input
                p0?.apply {
                    colors.filter {
                        it.startsWith(p0.trim(), true)
                    }.forEach {
                        // show the filtered list on text view
                        textView.append("\n$it")
                    }
                }
            }

            override fun afterTextChanged(p0: Editable?) {
                // do something after text changed
            }
        })
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="#DCDCDC"
    android:padding="32dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
android kotlin - EditText listener android kotlin - EditText listener 2
More android kotlin tutorials