Android 监听键盘弹出/隐藏

在部分安卓机型遇到 SoftInputMode 设置 adjustPan / adjustResize 无效的情况。于是对键盘做了单独的监听,方便统一处理

private int oldDiff = 0;

@Override
protected void onCreate(...) {
    listenKeyboardVisible();
}

private void listenKeyboardVisible() {
    final View activityRoot = getWindow().getDecorView();
    if (activityRoot ==null) {
        return;
    }
    mainContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        private final Rect r =new Rect();
        @Override
        public void onGlobalLayout() {
            activityRoot.getWindowVisibleDisplayFrame(r);
            int diff = activityRoot.getRootView().getHeight() -r.height();
            //键盘是否弹出
            boolean isOpen = (diff > 200);
            if(diff!=oldDiff){
                Log.d("keyboard", "keyboard open: "+isOpen);
                oldDiff = diff;

                // do someting...
                
            }
        }
    });
}

  

  

posted @ 2020-01-07 10:21  前端大兵  阅读(3252)  评论(0编辑  收藏  举报