How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event

本秂侑毒 提交于 2019-11-29 04:02:56

I was able to solve the same problem by sub-classing the dialog and hiding the keyboard before the cancel code on the dialog was executed.

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog dialog = new Dialog(getActivity(), getTheme()) {
        @Override public void cancel() {
            if (getActivity() != null && getView() != null) {
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
            }
            super.cancel();
        }

    };
    return dialog;
}

I tried many alternate approaches including using the DialogFragment's onCancel and onDimiss listeners to no avail. I believe the issue is that the listeners are called asynchronously while the dismiss/cancel is handled synchronously; so by the time your listener is called to hide the keyboard, the window token no longer exists.

This is what I did to get this to finally work... I needed to not use the widget for the keyboard... but use the currentfocus to get the windowtoken to remove the keyboard when a user selected something outside the dialog...

@Override
public void onStop() {
    // make sure the keyboard goes away when the user selects something outside the view (cancelled outside)
    if( Utilities.isValidActivity(this.getActivity())) {
        InputMethodManager imm = (InputMethodManager)this.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        // not the search view but the current focus at this point
        imm.hideSoftInputFromWindow(this.getActivity().getCurrentFocus().getWindowToken(), 0);                          
    }
    super.onStop();
}

I had the same issue and solved it by putting this in the AndroidManifest under the activity where I spawn the DialogFragment:

android:windowSoftInputMode="stateHidden"

Try adding an onDismissListener like this.

dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            // TODO Auto-generated method stub
            dismiss();
            }
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!