如何获得Android键盘的高度?

Kna*_*ina 3 keyboard android

如何获得Android键盘的高度?

我尝试:

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

但总是得到0.

小智 8

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

  • chatRootLayout是你的xml根布局
  • 在checkKeyboardHeight中将此rootLayout作为parentLayout参数传递

     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;
                        }
                    }
            });
    }
    
    Run Code Online (Sandbox Code Playgroud)

    }

这是changeKeyboardHeight()方法

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