Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android dismiss keyboard

Tags:

android

You want to disable or dismiss a virtual Keyboard?

If you want to just dismiss it you can use the following lines of code in your button's on click Event

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

The solution above doesn't work for all device and moreover it's using EditText as a parameter. This is my solution, just call this simple method:

private void hideSoftKeyBoard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    if(imm.isAcceptingText()) { // verify if the soft keyboard is open                      
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

This is my solution

public static void hideKeyboard(Activity activity) {
    View v = activity.getWindow().getCurrentFocus();
    if (v != null) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
}

you can also use this code on button click event

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Here's a Kotlin solution (mixing the various answers in thread)

Create an extension function (perhaps in a common ViewHelpers class)

fun Activity.dismissKeyboard() {
    val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
    if( inputMethodManager.isAcceptingText )
        inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0)
}

Then simply consume using:

// from activity
this.dismissKeyboard()

// from fragment
activity.dismissKeyboard()