Android Kotlin: EditText hide keyboard on lost focus

Android Kotlin - How to hide keyboard when EditText lost focus.

This code demonstrates how to hide the soft keyboard on an Android device when an EditText loses focus. It achieves this by setting an OnFocusChangeListener on the EditText and utilizing an extension function to programmatically hide the keyboard.

Breakdown:

  1. MainActivity.kt:
    • The MainActivity class extends the Activity class.
    • It declares two member variables: editText and textView to hold references to the EditText and TextView widgets from the layout.
    • In the onCreate method:
      • It inflates the layout resource using setContentView.
      • Finds the EditText and TextView by their IDs using findViewById.
      • Sets a OnFocusChangeListener on the editText. This listener is called whenever the focus state of the EditText changes (gains or loses focus).
    • The onFocusChangeListener checks the focus state:
      • If focused (has focus), it updates the textView text to indicate focus gained.
      • If unfocused (loses focus), it:
        • Updates the textView text to display the entered text in the EditText.
        • Calls the hideSoftKeyboard function to hide the keyboard.
  2. hideSoftKeyboard extension function:
    • This function is defined as an extension function for the Activity class.
    • It takes an EditText as a parameter.
    • It retrieves the InputMethodManager system service using getSystemService.
    • It then calls the hideSoftInputFromWindow method on the retrieved InputMethodManager instance, passing the EditText's window token and a flag (0 in this case). This hides the soft keyboard associated with the EditText.
  3. activity_main.xml:
    • This file defines the layout for the activity.
    • It uses a ConstraintLayout as the root layout.
    • It contains two elements:
      • An EditText with the ID editText.
      • A TextView with the ID textView.

Summary:

This code provides a clean and efficient way to manage keyboard visibility based on the focus state of an EditText in an Android Kotlin application. By leveraging the OnFocusChangeListener and the hideSoftKeyboard extension function, it offers a user-friendly experience by automatically hiding the keyboard when the user finishes entering text in the EditText.


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)

        // set edit text focus change listener
        editText.onFocusChangeListener = View.OnFocusChangeListener {
                p0, p1 ->
            if (p1){
                textView.text = "EditText focused."
            }else{
                // show edit text entered text when it unfocused
                textView.text = "EditText unfocused.\n\n${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="#004225"
        android:textSize="25sp"
        android:focusableInTouchMode="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editText"
        android:text="Focusable TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
android kotlin - EditText hide keyboard on lost focus android kotlin - EditText hide keyboard on lost focus 2
More android kotlin tutorials