Introduction
This code snippet showcases an approach to hide the soft keyboard on Android after pressing the enter key while typing in an EditText. It's written in Kotlin, a modern programming language for Android development. The code achieves this behavior by implementing a custom key listener for the EditText.
Breakdown
Setting Up the Layout:
- The
activity_main.xml
file defines the user interface layout consisting of an EditText and a TextView. The EditText is where the user types the text, and the TextView displays a message after the user presses enter.
- The
Initializing Variables:
- In
MainActivity.kt
, theonCreate
function retrieves references to the EditText, TextView, and ConstraintLayout usingfindViewById
.
- In
Creating a Key Listener:
- A custom
View.OnKeyListener
is defined. This listener gets triggered whenever a key is pressed on the EditText.
- A custom
Handling Enter Key Press:
Inside the key listener, the code checks for two conditions:
p2.action == KeyEvent.ACTION_DOWN
: This ensures the key is pressed down (not released).p1 == KeyEvent.KEYCODE_ENTER
: This verifies if the pressed key is the enter key.
If both conditions are met, the following actions are performed:
- The text entered in the EditText is retrieved and displayed in the TextView along with a message.
- The
hideSoftKeyboard
function is called to hide the keyboard programmatically. - Optionally, the focus is cleared from the EditText, and the cursor is hidden.
- Another optional step involves setting focus on the root ConstraintLayout (can be used for custom behavior).
Hiding the Keyboard:
- An extension function
hideSoftKeyboard
is defined for the Activity class. - This function retrieves the InputMethodManager service and uses it to hide the soft keyboard from the window associated with the currently focused view.
- An extension function
Summary
This code effectively demonstrates how to hide the keyboard on enter press in an EditText using a custom key listener. It provides clear separation of concerns by defining an extension function for hiding the keyboard. Additionally, it includes optional steps for managing focus and cursor visibility in the EditText.
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.content.Context.INPUT_METHOD_SERVICE
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
class MainActivity : Activity() {
private lateinit var editText:EditText
private lateinit var textView:TextView
private lateinit var constraintLayout:ConstraintLayout
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)
constraintLayout = findViewById(R.id.constraintLayout)
// initialize a new key listener instance
val keyListener = View.OnKeyListener { p0, p1, p2 ->
if(p2.action == KeyEvent.ACTION_DOWN
&& p1 == KeyEvent.KEYCODE_ENTER){
// perform action on enter key press
textView.text = "Enter Key Pressed \n\n${editText.text}"
// hide soft keyboard programmatically on enter key press
hideSoftKeyboard()
// optionally clear focus and hide cursor from edit text
editText.clearFocus()
editText.isCursorVisible = false
// optional, set focus on root constraint layout
constraintLayout.isFocusable = true
true
}else{
false
}
}
// add key listener for edit text
editText.setOnKeyListener(keyListener)
}
}
// extension function to hide soft keyboard programmatically
fun Activity.hideSoftKeyboard(){
(getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).apply {
hideSoftInputFromWindow(currentFocus?.windowToken, 0)
}
}
<?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:id="@+id/constraintLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#DCDCDC"
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="#4F42B5"
android:textSize="25sp"
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 - NumberPicker text size
- android kotlin - EditText space validation
- android kotlin - EditText email validation
- android kotlin - Show soft keyboard when EditText is focused
- android kotlin - EditText hide error
- android kotlin - EditText allow only numbers
- android kotlin - EditText allow only characters
- android kotlin - EditText limit number range
- android kotlin - EditText input filter decimal
- android kotlin - EditText remove underline while typing
- android kotlin - EditText change cursor color programmatically
- android kotlin - EditText hide keyboard click outside
- android kotlin - EditText enter key listener
- android kotlin - EditText listener
- android kotlin - EditText TextWatcher