3

How get height of Android Keyboard?

I try:

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

But always get 0.

Heshan Sandeepa
  • 3,388
  • 2
  • 35
  • 45
Knaus Irina
  • 789
  • 5
  • 15
  • 35

1 Answers1

9

Use OnGlobalLayoutListener for getting Keyboard height or implement above code snippet

  • 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);
        }
    }
    
Debasish Ghosh
  • 1,867
  • 20
  • 29
  • I use parentLayout as _activity.getWindow().getDecorView() and chatRootLayout as EditTextEx. And never call addOnGlobalLayoutListener – Knaus Irina Apr 16 '15 at 10:13
  • 1
    Call checkKeyboardHeight() method on your onCreate() and make sure that your parentLayout & chatRootLayout must be your xml root/main layout (whether it was Linear/Relative).. – Shekhar Mangrule Apr 16 '15 at 11:23
  • I try get height of virtual keyboard for Unity3d. I dont`t have xml layout – Knaus Irina Apr 18 '15 at 04:57