Hide Soft keyboard android code in Kotlin | programmatically?

Hiding a Soft keyboard in Android app is easy, just press the back button of the Android phone. But in some situations, it does not work, as a full-screen Activity.

Hide Soft keyboard android code in Kotlin

So How to Hide Soft keyboard android?

Let’s assume, we have an EditText and a Button in my layout. After click and writing in the edit field then clicking on the Button, we want to hide the virtual keyboard.

You can use Android with the following statement: Keyboard.hide(). That it but Android has a problem. You must use the InputMethodManager to hide the keyboard.

This is Android’s API to the keyboard. BUT! You are required to have a Context in order to get access to the IMM. Now we have a problem. I may want to hide the keyboard from a static or utility class that has no use or need for any Context. or And FAR worse, the IMM requires that you specify what View (or even worse, what Window) you want to hide the keyboard FROM.

This is what makes hiding the keyboard so challenging. Let’s do Close/hide the Android Soft Keyboard android application.

The main code in kotlin:-

Let’s see the step by step coding:-

Step 1. Create a new project “Build Your First Android App in Kotlin

Step 2. Open the “MainActivity.kt” and add the following code.

Step 3. Add EditText and Button in resources layout “activity_main.xml

Step 4. Now Run the application, in an emulator or on your Android device.

Output screenshot Android Keyboard hide app example :

Hide Soft keyboard android

Download source code Hide Soft keyboard android code in Kotlin


Note:  Clear focus to avoid showing keyboard again if you open the app from the background

Add this line to the end of the method:

Source: https://stackoverflow.com/

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in Android Studio 3.3.2. Tested on Android 9 ( Android-P), compile SDK version API 28: Android 9.0 (Pie)
Coding in Kotlin

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.