How to check visibility of software keyboard in Android?

前端 未结 30 4488
半阙折子戏
半阙折子戏 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:35

    There is also solution with system insets, but it works only with API >= 21 (Android L). Say you have BottomNavigationView, which is child of LinearLayout and you need to hide it when keyboard is shown:

    > LinearLayout
      > ContentView
      > BottomNavigationView
    

    All you need to do is to extend LinearLayout in such way:

    public class KeyboardAwareLinearLayout extends LinearLayout {
        public KeyboardAwareLinearLayout(Context context) {
            super(context);
        }
    
        public KeyboardAwareLinearLayout(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        public KeyboardAwareLinearLayout(Context context,
                                         @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        public KeyboardAwareLinearLayout(Context context, AttributeSet attrs,
                                         int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        @Override
        public WindowInsets onApplyWindowInsets(WindowInsets insets) {
            int childCount = getChildCount();
            for (int index = 0; index < childCount; index++) {
                View view = getChildAt(index);
                if (view instanceof BottomNavigationView) {
                    int bottom = insets.getSystemWindowInsetBottom();
                    if (bottom >= ViewUtils.dpToPx(200)) {
                        // keyboard is shown
                        view.setVisibility(GONE);
                    } else {
                        // keyboard is hidden
                        view.setVisibility(VISIBLE);
                    }
                }
            }
            return insets;
        }
    }
    

    The idea is that when keyboard is shown, system insets are changed with pretty big .bottom value.

提交回复
热议问题