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:
- MainActivity.kt:
- The
MainActivity
class extends theActivity
class. - It declares two member variables:
editText
andtextView
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
andTextView
by their IDs usingfindViewById
. - Sets a
OnFocusChangeListener
on theeditText
. This listener is called whenever the focus state of the EditText changes (gains or loses focus).
- It inflates the layout resource using
- 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.
- Updates the
- If focused (has focus), it updates the
- The
- 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 usinggetSystemService
. - It then calls the
hideSoftInputFromWindow
method on the retrievedInputMethodManager
instance, passing theEditText
's window token and a flag (0 in this case). This hides the soft keyboard associated with the EditText.
- This function is defined as an extension function for the
- 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 IDeditText
. - A
TextView
with the IDtextView
.
- An
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 - Volley JsonArrayRequest
- android kotlin - Volley JsonObjectRequest
- android kotlin - Chip border color
- android kotlin - Chip background color
- android kotlin - ChipGroup single selection
- android kotlin - NumberPicker string values
- android kotlin - EditText space validation
- android kotlin - EditText email validation
- android kotlin - EditText limit number range
- android kotlin - EditText input filter decimal
- android kotlin - EditText set max length programmatically
- android kotlin - EditText remove underline while typing
- android kotlin - EditText change cursor color programmatically
- android kotlin - EditText change underline color programmatically
- android kotlin - EditText focus change listener