In this article, we will add the listener to the editText using addTextChangedListener with the lambda functions.

Using the addTextChangedListener, we can attach a watcher to the editText view. This function will be called when the text changes in the editText.

Instead of writing the anonymous inner class, we can use the lambda expressions as a listener for text change events.

Following is the example:

In the below example, we have an EditText view with an id editText and a TextView view with an id textView. We passed the lambda expression as an argument to the editText and inside it, we just check the length of the entered text. If the length of the text is more than 5 characters, we set the text of the textView to “Text is too long“. Otherwise, we just display the length of the text.

val editText: EditText = findViewById(R.id.editText)
val textView: TextView = findViewById(R.id.textView)

editText.addTextChangedListener { text ->
    if (text.length > 5) {
        textView.text = "Text is too long"
    } else {
        textView.text = "Text length: ${text.length}"
    }
}

Categorized in:

Tagged in:

,