android 监听软键盘在页面的展开和隐藏

获取软键盘状态思路:

  1. 获取当前页面根布局及其高度 RootH;
  2. 获取状态栏高度 StatusH和导航栏高度 NavigationH;
  3. 获取当前根视图在屏幕上显示的高度RectH;
  4. 高度差值比较,(根布局高度 - 根视图显示高度)与(状态栏高度 + 导航栏高度)的大小对比;
  5. 大于:展开软键盘
  6. 小于:隐藏软键盘

相关代码块:

viewTree的监听

// viewTree的监听
private ViewTreeObserver.OnGlobalLayoutListener keyboardLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            
            // 显示的根视图 
            Rect r = new Rect();
            rootLayout.getWindowVisibleDisplayFrame(r);
            
            // 导航栏对象
            Point navigationBarHeight = SystemUtils.getNavigationBarSize(InformationBaseActivity.this);

            // 状态栏高度
            int statusBarHeight = SystemUtils.getStatusBarHeight(InformationBaseActivity.this);
            Log.e(TAG, "navigationBarHeight " + navigationBarHeight.x + " " + navigationBarHeight.y + statusBarHeight);

            // (r.bottom - r.top) 当前页面根视图显示的高度
            // heightDiff 当前页面原本根布局高度与显示视图的高度差
            int heightDiff = rootLayout.getRootView().getHeight() - (r.bottom - r.top);

            // 高度差判断是否弹出软键盘
            if (heightDiff > (100 + navigationBarHeight.y + statusBarHeight)) { // if more than 100 pixels, its probably a keyboard...
                mIsShowSoft = true;
                onShowKeyboard(heightDiff);
            } else {
                if (mIsShowSoft) {
                    onHideKeyboard();
                    mIsShowSoft = false;
                }
            }
        }
    };

根布局对viewTree的实时监听

 protected void attachKeyboardListeners(int rootViewId) {
        if (keyboardListenersAttached) {
            return;
        }
        rootLayout = findViewById(rootViewId);
        rootLayout.getViewTreeObserver().addOnGlobalLayoutListener(keyboardLayoutListener);

        keyboardListenersAttached = true;
    }

页面销毁时移除监听

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (keyboardListenersAttached) {
            rootLayout.getViewTreeObserver().removeGlobalOnLayoutListener(keyboardLayoutListener);
        }
    }

如何使用:

这些软键盘的监听操作可部署到基类中,需要用时可调用基类中的attachKeyboardListeners(),onShowKeyboard()和onHideKeyboard()方法进行相对应的操作。

项目下载地址

猜你喜欢

转载自blog.csdn.net/L0123456L/article/details/82887407