How to check visibility of software keyboard in Android?

前端 未结 30 4510
半阙折子戏
半阙折子戏 2020-11-21 04:43

I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?

30条回答
  •  [愿得一人]
    2020-11-21 05:28

    Here's my solution, and it works. Instead of looking for pixel size just check that the height of the content view has changed or not:

    // Scroll to the latest comment whenever the keyboard is shown
    commentsContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    
            private int oldHeight;
    
            @Override
            public void onGlobalLayout() {
                int newHeight = commentsContent.getMeasuredHeight();
                if (newHeight < oldHeight) {
                    // Check for the keyboard showing in case the height difference
                    // is a result of orientation change
                    if (isSoftKeyboardShowing(CommentsActivity.this)) {
                        // Keyboard is showing so scroll to the latest comment
                        scrollToLatestComment();
                    }
                }
                oldHeight = newHeight;
            }
    
        });
    
    
    public static boolean isSoftKeyboardShowing(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        return inputMethodManager.isActive();
    }
    

提交回复
热议问题