在Lollipop中获取键盘高度

5
在Lollipop中键盘高度有什么变化?
在Lollipop之前,我使用了一个方法,正确地使用getViewTreeObserver()返回了键盘的高度(在ldpi、mdpi、hdpi和xhdpi上测试无问题),但在Lollipop上似乎返回的高度比实际键盘的高度略高。
在我的Asus Nexus 7上,我得到的高度比实际高度大约70像素。
有人知道如何在Lollipop上获取真正的键盘高度吗?

Nexus 5和Moto G运行Lollipop也是如此。到目前为止有什么解决方案吗? - Gaurav Bhor
1个回答

3
当键盘弹出时,请尝试以下代码。
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public int calculateScreenHeightForLollipop() {
    WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);
    return size.y;
}

/**
 * Call this function to resize the emoji popup according to your soft keyboard size
 */
public void setSizeForSoftKeyboard() {
    rootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            rootView.getWindowVisibleDisplayFrame(r);
            int screenHeight;
            if (Build.VERSION.SDK_INT >= 5.0) {
                screenHeight = calculateScreenHeightForLollipop();
            } else {
                screenHeight = rootView.getRootView().getHeight();
            }
            int heightDifference = screenHeight
                    - (r.bottom - r.top);
            int resourceId = mContext.getResources()
                    .getIdentifier("status_bar_height",
                            "dimen", "android");
            if (resourceId > 0) {
                heightDifference -= mContext.getResources()
                        .getDimensionPixelSize(resourceId);
            }
            if (heightDifference > 100) {
                keyBoardHeight = heightDifference;
                setSize(LayoutParams.MATCH_PARENT, keyBoardHeight);
                if (!isOpened) {
                    if (onSoftKeyboardOpenCloseListener != null)
                        onSoftKeyboardOpenCloseListener.onKeyboardOpen(keyBoardHeight);
                }
                isOpened = true;
                if (pendingOpen) {
                    showAtBottom();
                    pendingOpen = false;
                }
            } else {
                isOpened = false;
                if (onSoftKeyboardOpenCloseListener != null)
                    onSoftKeyboardOpenCloseListener.onKeyboardClose();
            }
        }
    });
}

我认为应该是:if (Build.VERSION.SDK_INT >= 21),对吗? - Frank Nguyen
@FrankNguyen 是的,应该是 if (Build.VERSION.SDK_INT >= 21)。 - iAviatorJose

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接