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
MainActivityclass extends theActivityclass. - It declares two member variables:
editTextandtextViewto hold references to the EditText and TextView widgets from the layout. - In the
onCreatemethod:- It inflates the layout resource using
setContentView. - Finds the
EditTextandTextViewby their IDs usingfindViewById. - Sets a
OnFocusChangeListeneron theeditText. This listener is called whenever the focus state of the EditText changes (gains or loses focus).
- It inflates the layout resource using
- The
onFocusChangeListenerchecks the focus state:- If focused (has focus), it updates the
textViewtext to indicate focus gained. - If unfocused (loses focus), it:
- Updates the
textViewtext to display the entered text in the EditText. - Calls the
hideSoftKeyboardfunction 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
Activityclass. - It takes an
EditTextas a parameter. - It retrieves the
InputMethodManagersystem service usinggetSystemService. - It then calls the
hideSoftInputFromWindowmethod on the retrievedInputMethodManagerinstance, 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
ConstraintLayoutas the root layout. - It contains two elements:
- An
EditTextwith the IDeditText. - A
TextViewwith 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