用 ViewTreeObserver() 检测键盘是否显示

143 阅读1分钟
 final LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);
    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int heightDiff = rootView.getRootView().getHeight() - rootView.getHeight();
            if (heightDiff > DensityUtil.dp2px(ChatActivity.this, 200)) { //如果view的高度大于200dp,那么很有可能就是键盘
                isKeyboardVisible = true;
            } else {
                isKeyboardVisible = false;
            }
        }
    });