Hide keyboard in AlertDialog

I found the solution :

alert.setNegativeButton(cancel,
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            saveimage();
            InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(input.getWindowToken(), 0);
            dialog.cancel();
        }
    });

I should've put dialog.cancel() after I hide the keyboard.

UPDATE IN KOTLIN:

val im: InputMethodManager =
    getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
im.hideSoftInputFromWindow(editText.windowToken, 0)

I too was struggling with this and bonked my head on just about every "solution" which was posted yet the damn keyboard would still not close. Then I had a caffenated vision:

            InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(dialog.getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
        }

Note the HIDE_IMPLICIT_ONLY

hope that helps anyone else struggling with this problem.


In my case i wanted keyboard to be open only when the dialog shown i have tried many solutions but finally i have succeeded to achieve by adding

 android:windowSoftInputMode="stateAlwaysHidden"

inside tag of manifiest file.