Skip to content
Related Articles

Related Articles

Improve Article

How to programmatically hide Android soft keyboard

  • Difficulty Level : Easy
  • Last Updated : 23 Feb, 2021

In this article, we will learn about how to hide soft keyboard programmatically. The keyboard generally hides but there are certain instances when it does not hide. So for better user experience, the keyboard is hidden programmatically.

Without using below approach, the default response of the app is shown below:-


  1. Now add the following code in the activity_main.xml file. The below code adds a textview, edittext and a button in activity_main. The button when clicked invokes the setText function in MainActivity class.


    <?xml version="1.0" encoding="utf-8"?>
            android:textSize="22sp" />
            android:layout_height="wrap_content" />
            android:text="Set Text" />

  2. Now add the following code in the file. Here we define the setText and closeKeyboard function. The setText function is invoked when the user clicks the button. It takes the input from edittext and replaces it in the textview. Then it calls the closeKeyboard function and clears the value of edittext. The closeKeyboard function hides the keyboard.

    package org.geeksforgeeks.gfgHideKey
        import android.content.Context;
    import android.os.Bundle;
    import android.view.View;
    import android.view.inputmethod
    import android.widget.EditText;
    import android.widget.TextView;
    public class MainActivity
        extends AppCompatActivity {
        private TextView textViewResult;
        private EditText editTextInput;
        protected void onCreate(
            Bundle savedInstanceState)
                = findViewById(
                = findViewById(
        public void setText(View v)
            String newText
                = editTextInput
        private void closeKeyboard()
            // this will give us the view
            // which is currently focus
            // in this layout
            View view = this.getCurrentFocus();
            // if nothing is currently
            // focus then this will protect
            // the app from crash
            if (view != null) {
                // now assign the system
                // service to InputMethodManager
                InputMethodManager manager
                    = (InputMethodManager)
                        view.getWindowToken(), 0);


Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :