Hide soft keyboard after dialog dismiss

Viewed 36975

I want to hide soft keyboard after AlertDialog dismiss, but it's still visible. Here is my code:

alert = new AlertDialog.Builder(MyActivity.this);
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

alert.setOnDismissListener(new DialogInterface.OnDismissListener() {

    @Override
    public void onDismiss(DialogInterface dialog) {
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
});
8 Answers

This works! This will close the keyboard after dialog dismiss

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
protected void hideKeyboard() {
    final Activity activity = getActivity();
    final View view = activity != null ? activity.getCurrentFocus() : null;
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null)
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
    }, 1);
}

@Override
public void onDismiss(DialogInterface dialog) {
    super.onDismiss(dialog);
    hideKeyboard();
}

in case anyone looks for this in kotlin, it would be:

private fun hideDeviceKeyboard() {
    val imm = context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
Related