How to check visibility of software keyboard in Android?

前端 未结 30 4440
半阙折子戏
半阙折子戏 2020-11-21 04:43

I need to do a very simple thing - find out if the software keyboard is shown. Is this possible in Android?

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 05:18

    It has been forever in terms of the computer but this question is still unbelievably relevant! So I've taken the above answers and have combined and refined them a bit...

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }
    
    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
            private boolean wasOpened;
    
        private final Rect r = new Rect();
    
            @Override
            public void onGlobalLayout() {
                activityRootView.getWindowVisibleDisplayFrame(r);
    
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isOpen = heightDiff > 100;
                if (isOpen == wasOpened) {
                    logDebug("Ignoring global layout change...");
                    return;
                }
    
                wasOpened = isOpen;
                listener.onVisibilityChanged(isOpen);
            }
        });
    }
    

    It works for me.

提交回复
热议问题