Android Kotlin: EditText focus change listener

Implementing Focus Change Listener for an EditText in Android with Kotlin

This code demonstrates how to listen for focus changes in an EditText widget within an Android Activity written in Kotlin. It provides a clear separation between the layout definition (activity_main.xml) and the activity logic (MainActivity.kt).

The code achieves the following functionalities:

  1. Focus Change Listener: It sets an OnFocusChangeListener on the EditText. This listener gets notified whenever the EditText gains or loses focus.
  2. Focus Gained: When the EditText gains focus, the text displayed in the TextView is updated to indicate "EditText now focused."
  3. Focus Lost: When the EditText loses focus, the TextView is updated with multiple messages:
    • "EditText lost focus."
    • "Soft keyboard hide." (This informs the user that the keyboard is hidden)
    • The actual text entered in the EditText is displayed with a label "You entered : ".
  4. Hiding Soft Keyboard: The code defines an extension function hideSoftKeyboard that hides the soft keyboard programmatically when the EditText loses focus.

Overall, this code snippet showcases a practical approach to handling focus changes in an EditText and provides informative feedback to the user through the TextView.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context.INPUT_METHOD_SERVICE
import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
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)

        // click on the root constraint layout blank area
        // to remove focus from the edit text
        textView.text = "Click outside to remove focus from edit text."


        // set edit text focus change listener
        editText.onFocusChangeListener  = View.OnFocusChangeListener {
                view, b ->
            if (b){
                // do something when edit text get focus
                textView.text = "EditText now focused."
            }else{
                // do something when edit text lost focus
                textView.text = "EditText lost focus."
                textView.append("\nSoft keyboard hide.")
                textView.append("\n\nYou entered : ${editText.text}")

                // hide soft keyboard when edit text lost focus
                hideSoftKeyboard(editText)
            }
        }
    }
}


// extension function to hide soft keyboard programmatically
fun Activity.hideSoftKeyboard(editText: EditText){
    (getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).apply {
        hideSoftInputFromWindow(editText.windowToken, 0)
    }
}
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:focusableInTouchMode="true"
    android:focusable="true"
    android:clickable="true"
    android:padding="32dp">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        android:inputType="text"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.12" />

    <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="#5D3954"
        android:textSize="26sp"
        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 focus change listener android kotlin - EditText focus change listener 2
More android kotlin tutorials