Null pointer error with hideSoftInputFromWindow

后端 未结 14 739
逝去的感伤
逝去的感伤 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 11:48

    As CommonsWare mentioned, the getCurrentFocus() is null, since there is no View component inside the current Activity holding the focus.

    If you already have a view in your Activity, use it to get the window token. For example, if I have a Button component:

    inputManager.hideSoftInputFromWindow(myButton.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    

    Or even worse, if I do not have any view already in my Activity, I could do this:

    inputManager.hideSoftInputFromWindow(new View(this).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    

    This would solve your problem of NPE, but I hope you find the description useful.

    One more thing about keyboards is that when user presses the back button while the keyboard is visible, the keyboard receives and consumes the back key press to hide itself. Or at least most keyboards behave that way.

提交回复
热议问题