Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keyboard height in Lollipop

What did change in Lollipop about keyboard height?

I had a method which using getViewTreeObserver() correctly returned the height of the keyboard on every version before Lollipop (tested on ldpi, mdpi, hdpi and xhdpi - no problems) but it seems that on Lollipop the height returned is a little bit larger that the real keyboard's height.

On my Asus Nexus 7 I got a height with about 70 px larger than the actual height.

Does anybody know how to get the real keyboard's height on Lollipop?

like image 419
stanga bogdan Avatar asked Oct 19 '22 18:10

stanga bogdan


1 Answers

Try This Following Code When the Keyboard Opens Up.

@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();
            }
        }
    });
}
like image 165
iAviatorJose Avatar answered Oct 22 '22 07:10

iAviatorJose