如何获取 Android 键盘的高度?

How to get the Height of Android Keyboard?

如何获取Android键盘的高度?

我试试:

KeyboardView keyboardView = new KeyboardView(_activity.getApplicationContext(), null);
Log.i("","xxx height " + keyboardCustom.mKeyboardView.getHeight());
            Log.i("","xxx height " + keyboardCustom.mKeyboardView.getBottom());

但总是得到0。

使用 OnGlobalLayoutListener 获取键盘高度或实现上面的代码片段

  • chatRootLayout 是您的 xml 根布局
  • 将此 rootLayout 作为 parentLayout 参数传递给 checkKeyboardHeight

     private void checkKeyboardHeight(final View parentLayout)
        {
          chatRootLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() 
          {
                @Override
                public void onGlobalLayout() 
                {
                        Rect r = new Rect();
    
                        chatRootLayout.getWindowVisibleDisplayFrame(r);
    
                        int screenHeight = chatRootLayout.getRootView().getHeight();
                        int keyboardHeight = screenHeight - (r.bottom);
    
                        if (previousHeightDiffrence - keyboardHeight > 50) 
                        {                           
                            // Do some stuff here
                        }
    
                        previousHeightDiffrence = keyboardHeight;
                        if (keyboardHeight> 100) 
                        {
                            isKeyBoardVisible = true;
                            changeKeyboardHeight(keyboardHeight);
                        } 
                        else
                        {
                            isKeyBoardVisible = false;
                        }
                    }
            });
    }
    

    这是 changeKeyboardHeight() 方法

    private void changeKeyboardHeight(int height) 
    {
        if (height > 100) 
        {
                keyboardHeight = height;
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, keyboardHeight);
                yourLayout.setLayoutParams(params);
        }
    }