Android Kotlin: How to implement Text Watcher for an EditText

Android Kotlin - How to implement Text Watcher for an EditText

This code demonstrates how to monitor text changes within an EditText widget using Kotlin in an Android application. It achieves this functionality by implementing the TextWatcher interface and attaching it to the desired EditText.

Explanation:

  1. Setting Up the Activity:

    • The MainActivity class extends the Activity class, which is the base class for most Android activities.
    • It defines two member variables: editText and textView of types EditText and TextView respectively, to hold references to the corresponding UI elements from the layout.
  2. Initializing the Layout:

    • In the onCreate method, the activity inflates the layout file activity_main.xml using setContentView.
    • It then retrieves references to the EditText and TextView using findViewById and assigns them to the member variables.
  3. Implementing Text Watcher:

    • An anonymous inner class that implements the TextWatcher interface is created.
    • This interface has three callback methods:
      • beforeTextChanged: This method is called before the text is changed but after any selection is changed. (Not used in this example)
      • onTextChanged: This method is called after the text has been changed and after any selection is changed. Here, it updates the textView content with the current text from the EditText along with a message.
      • afterTextChanged: This method is called after the text has been changed, but before any selection is changed. (Not used in this example)
  4. Attaching Text Watcher:

    • The addTextChangedListener method of the editText is called. This method takes a TextWatcher object as a parameter. Here, the anonymous inner class implementing TextWatcher is passed as the argument.
  5. Layout File (activity_main.xml):

    • This file defines the user interface for the activity using ConstraintLayout.
    • It contains two elements:
      • An EditText which allows the user to input text.
      • A TextView that displays a message and the current text entered in the EditText.

Summary

This code snippet showcases a basic implementation of monitoring text changes in an EditText. By attaching a TextWatcher to the EditText, the application can perform various actions based on user input, such as validating the entered text, updating other UI elements, or performing real-time calculations. The example demonstrates updating a TextView with the current text from the EditText.


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)

        // 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 = "On text changed\n\n$p0"
            }

            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="32dp"
        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="32dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#1034A6"
        android:textSize="30sp"
        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 TextWatcher android kotlin - EditText TextWatcher 2
More android kotlin tutorials