监听全局键盘的弹出与隐藏状态

android自带的监听方法不靠谱,可以通过根view的可见高度来判断键盘的显示与隐藏状态,但不适应于activity为全屏的状态。

wholeLayout.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);

 /**
 * 全局监听软键盘的显示状态
 */
private ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        // 应用可以显示的区域。此处包括应用占用的区域,包括标题栏不包括状态栏
        Rect r = new Rect();
        wholeLayout.getWindowVisibleDisplayFrame(r);
        // 键盘最小高度
        int minKeyboardHeight = 150;
        // 屏幕高度,不含虚拟按键的高度
        int screenHeight = wholeLayout.getRootView().getHeight();
        // 获取状态栏高度
        int statusBarHeight = r.top;
        // 在不显示软键盘时,height等于状态栏的高度
        int height = screenHeight - (r.bottom - r.top);
        //Log.i("wyy", "onGlobalLayout: height = " + height + ", staheight  =" + statusBarHeight + ", r.top = " + r.top + ", r.bottom = " + r.bottom);

        if (ShowKeyboard) {
            // 如果软键盘是弹出的状态,并且height小于等于状态栏高度,
            // 说明这时软键盘已经收起
            if (height - statusBarHeight < minKeyboardHeight) {
                //ToastUtils.showToast(GoodsAllStockActivity.this, "键盘隐藏了");
                resetAnimation();
                ShowKeyboard = false;
                if (!searchEditText.getText().toString().equals("")) {
                    gotoSearch();
                }
            }
        } else {
            // 如果软键盘是收起的状态,并且height大于状态栏高度,
            // 说明这时软键盘已经弹出
            if (height - statusBarHeight > minKeyboardHeight) {
                ShowKeyboard = true;
                //ToastUtils.showToastToastUtils.showToast(GoodsAllStockActivity.this,"键盘显示了");
            }
        }
    }
};

猜你喜欢

转载自blog.csdn.net/sindyue/article/details/68483327
今日推荐