Tried hideSoftInputFromWindow does not work, only toggleSoftInput. But this method is: when the input method is hidden, it will be displayed; when the input method is displayed, it will be hidden. My application scenario is to hide the input method when dialogFragment is closed. If the input method itself is hidden, the input method will be displayed, which is wrong. Therefore, a judgment should be added to determine whether the input method is a display state (refer to https://www.jianshu.com/p/2bdb4018b6d1)
private boolean isInputMethodShowing() { //Get the height of the current screen content int screenHeight = getActivity().getWindow().getDecorView().getHeight(); //Get the bottom of the View visible area Rect rect = new Rect(); getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect); return screenHeight - rect.bottom - getSoftButtonsBarHeight() != 0; } /** * Height of the bottom virtual key bar * @return */ @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) private int getSoftButtonsBarHeight() { DisplayMetrics metrics = new DisplayMetrics(); //This method may not get the height of the real screen getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); int usableHeight = metrics.heightPixels; //Get the real height of the current screen getActivity().getWindowManager().getDefaultDisplay().getRealMetrics(metrics); int realHeight = metrics.heightPixels; if (realHeight > usableHeight) { return realHeight - usableHeight; } else { return 0; } }
Then hide the input method
//If the input method is already displayed on the window, it will be hidden, otherwise it will be displayed private void hideSoftInputWindow(Context context) { InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); if(isInputMethodShowing()) { LogUtils.i("hideSoftInputWindow:"); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); } }