Skip to main content

How to show or hide the soft keyboard for an EditText in Kotlin Android

How to show or hide the soft keyboard for an EditText in Kotlin Android.

Here is a detailed step-by-step tutorial on how to show or hide the soft keyboard for an EditText in Kotlin Android.

Step 1: Create a new Android project

Start by creating a new Android project in Android Studio. Choose an appropriate project name and set the minimum SDK version to at least 21.

Step 2: Design the layout

Open the activity_main.xml layout file and add an EditText to capture user input. You can also add a Button to demonstrate how to show/hide the soft keyboard. Here's an example layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context=".MainActivity">

<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text" />

<Button
android:id="@+id/buttonToggleKeyboard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editText"
android:text="Toggle Keyboard" />

</RelativeLayout>

Step 3: Initialize views in MainActivity

Open the MainActivity.kt file and initialize the EditText and Button views in the onCreate method. You will also need to set an OnClickListener for the Button.

import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val buttonToggleKeyboard = findViewById<Button>(R.id.buttonToggleKeyboard)
buttonToggleKeyboard.setOnClickListener {
toggleSoftKeyboard()
}
}

private fun toggleSoftKeyboard() {
val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
if (imm.isActive) {
imm.hideSoftInputFromWindow(editText.windowToken, 0)
} else {
imm.showSoftInput(editText, 0)
}
}
}

Step 4: Test the app

Build and run the app on an emulator or physical device. You should see the EditText and Button displayed on the screen. Tap the Button to show or hide the soft keyboard.

That's it! You have successfully implemented the functionality to show or hide the soft keyboard for an EditText in Kotlin Android.

Note: Make sure to handle cases where the soft keyboard may already be hidden or shown. This tutorial provides a basic implementation, but you may need to modify it based on your specific requirements.