如何获取Android键盘的高度?

3

如何获取Android键盘的高度?

我尝试了以下方法:

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

但总是得到0。

你的键盘可见吗? - playmaker420
请参考以下链接:https://dev59.com/Hm025IYBdhLWcg3wblc3 - Krupa Patel
这总是一个错误的问题(特别是在浮动键盘上)。你实际上想做什么? - ianhanniballake
你为什么想要键盘的高度? - Thomas Vos
我需要获取虚拟安卓键盘的高度,以便在虚拟键盘上方放置一些图片。 - Knaus Irina
1个回答

9
使用OnGlobalLayoutListener来获取键盘高度或者实现上述代码片段。
  • chatRootLayout is your xml root layout
  • pass this rootLayout as parentLayout parameter in 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;
                        }
                    }
            });
    }
    

    Here is changeKeyboardHeight() method

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

我使用parentLayout作为_activity.getWindow().getDecorView(),chatRootLayout作为EditTextEx。并且从未调用addOnGlobalLayoutListener。 - Knaus Irina
1
在onCreate()中调用checkKeyboardHeight()方法,并确保你的parentLayout和chatRootLayout必须是你的xml根/主布局(无论它是Linear/Relative)。 - Shekhar Mangrule
我正在尝试获取Unity3d虚拟键盘的高度。我没有XML布局。 - Knaus Irina

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接