January 3, 2017

How to Hide and Show Soft Keyboard in Android

By Lalit Vasan


There may be a case where you want to hide or show the soft keyboard. The case may be for example, you are done with entering text in search view and based on your selection from the suggestion list you want to take some action and also want to close (hide) the soft keyboard. You can hide or show the soft keyboard programmatically in Android by using the InputMethodManager. You can hide and show the keyboard programmatically with the following methods. Call the below methods by passing EditText, SearchView or any view object in it.

Hiding Soft Keyboard

 public void hideSoftKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

Showing Soft Keyboard

 public void showSoftKeyboard(View view) {
        if (view.requestFocus()) {
            InputMethodManager imm = (InputMethodManager)
                    getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }
Usage
EditText editText = (EditText) findViewById(R.id.editText);
 // hiding the soft keyboard
 hideSoftKeyboard(editText);
 // showing the soft keyboard
 showSoftKeyboard(editText);

Enjoy Coding and Share Knowledge