How to get the Height of Android Keyboard?

16,280

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);
        }
    }
    
Share:
16,280
Knaus Irina
Author by

Knaus Irina

Updated on June 05, 2022

Comments

  • Knaus Irina
    Knaus Irina almost 2 years

    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.

  • Knaus Irina
    Knaus Irina about 9 years
    I use parentLayout as _activity.getWindow().getDecorView() and chatRootLayout as EditTextEx. And never call addOnGlobalLayoutListener
  • Shekhar Mangrule
    Shekhar Mangrule about 9 years
    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)..
  • Knaus Irina
    Knaus Irina about 9 years
    I try get height of virtual keyboard for Unity3d. I dont`t have xml layout