How to close Android Soft KeyBoard programmatically?

前端 未结 14 1342
别跟我提以往
别跟我提以往 2020-12-02 16:33

I am currently showing softkeyboard using the following code

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im         


        
14条回答
  •  我在风中等你
    2020-12-02 17:23

    Here is s solution, which checks if keyboard is visible

        public static void hideKeyboard(Activity activity) {
            if (isKeyboardVisible(activity)) {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
            }
        }
    
        public static boolean isKeyboardVisible(Activity activity) {
            ///This method is based on the one described at http://stackoverflow.com/questions/4745988/how-do-i-detect-if-software-keyboard-is-visible-on-android-device
            Rect r = new Rect();
            View contentView = activity.findViewById(android.R.id.content);
            contentView.getWindowVisibleDisplayFrame(r);
            int screenHeight = contentView.getRootView().getHeight();
    
            int keypadHeight = screenHeight - r.bottom;
    
            return
                    (keypadHeight > screenHeight * 0.15);
        }
    

提交回复
热议问题