在Lollipop获得键盘高度

时间:2015-01-25 10:44:19

标签: android keyboard height android-5.0-lollipop android-4.4-kitkat

Lollipop在键盘高度上有什么变化?

我有一个方法,使用getViewTreeObserver()正确地返回Lollipop之前的每个版本的键盘高度(在ldpi,mdpi,hdpi和xhdpi上测试 - 没有问题)但似乎在Lollipop上返回的高度是真正的键盘高度稍微大一些。

在我的Asus Nexus 7上,我的高度比实际高度大约70 px。

有人知道如何在Lollipop上获得真正的键盘高度吗?

1 个答案:

答案 0 :(得分: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();
            }
        }
    });
}
相关问题