Android custom keyboard - Preview view constrained to parent layout

后端 未结 3 1353
清歌不尽
清歌不尽 2020-12-30 10:06

I have created a custom keyboard, which works fine - except the preview views for the top two rows of keys are not displayed high enough. Their vertical position is being co

3条回答
  •  死守一世寂寞
    2020-12-30 10:47

    For anyone coming here in the future, I recommend not using KeyboardView. At least at the time of this writing (API 27), it hasn't been updated for a long time. The problem described in the question above is just one of its many shortcomings.

    It is more work, but you can make your own custom view to use as a keyboard. I describe that process at the end of this answer.

    When you create the popup preview window in your custom keyboard, you need to call popupWindow.setClippingEnabled(false) in order to get the popup window to display above the keyboard for Android API 22+. (Thanks to this answer for that insight.)

    Here is an example in context from one of my recent projects.

    private void layoutAndShowPopupWindow(Key key, int xPosition) {
        popupWindow = new PopupWindow(popupView,
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setClippingEnabled(false);// <-- let popup display above keyboard
        int location[] = new int[2];
        key.getLocationInWindow(location);
        int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        popupView.measure(measureSpec, measureSpec);
        int popupWidth = popupView.getMeasuredWidth();
        int spaceAboveKey = key.getHeight() / 4;
        int x = xPosition - popupWidth / popupView.getChildCount() / 2;
        int y = location[1] - popupView.getMeasuredHeight() - spaceAboveKey;
        popupWindow.showAtLocation(key, Gravity.NO_GRAVITY, x, y);
    
        // using popupWindow.showAsDropDown(key, 0, yOffset) might be
        // easier than popupWindow.showAtLocation() 
    }
    

提交回复
热议问题