Null pointer error with hideSoftInputFromWindow

后端 未结 14 567
逝去的感伤
逝去的感伤 2020-12-25 11:32

I get a null pointer exception at this row:

public void hideKeyboard(){ 
InputMethodManager inputManager = (InputMethodManager)            
            this.         


        
14条回答
  •  时光说笑
    2020-12-25 12:05

    I just need to check if there is a focused view before hiding the keyboard.

    For example, if you have an EditText in your activity or fragment, it'll probably be the focused view. When the EditText isn't focused anymore, getCurrentFocus() may return null (unless some other view is focused).

    void hideKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(
                Context.INPUT_METHOD_SERVICE);
        View focusedView = getActivity().getCurrentFocus();
        /*
         * If no view is focused, an NPE will be thrown
         * 
         * Maxim Dmitriev
         */
        if (focusedView != null) {
            inputManager.hideSoftInputFromWindow(focusedView.getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    

提交回复
热议问题