Get the height of virtual keyboard in Android
Asked Answered
T

6

15

How can I get the height of virtual keyboard in Android? Is it possible?

I try to get it from the main window, but it gives me full height of the application. But I want to get the keyboard height.

Thicken answered 15/5, 2011 at 15:55 Comment(5)
The soft keyboard isn't the only system-supplied decoration that can consume screen space. What do you intend to do with this size?Cabretta
I want to draw some images top of the soft virtualkeyboard. I develop 2D application, so I dont use android UI library. for example, I want to draw border top of the soft keyboardThicken
Doesn't the virtual keyboard push the window upwards? In that case, all you need is a line at the bottom of the screen to draw a top border (that's set to invisible until softkeyboard is activated)Crinkleroot
It only pushes the window upwards if it is not in fullscreen.Mow
Take a look at my answer here.Brutus
A
4

You can't get the keyboard height, but you can get the height of your View, which is what you really want - and you'll get this data supplied to the onLayout call into the current view.

Aright answered 16/6, 2011 at 16:59 Comment(2)
my view gives full height of device. so, this info doesnt give virtual keyboard height. but, I found a way to get it. After I request to open virtual keyboard, I send pointer event that I generate. their y coordinate starts from height of device and decreases. and, after I send these event to system, system throws exception when pointer event is on virtual keyboard. if these pointer events is not on virtual keyboard, there is no exception. so I can get height of virtual keyboard.Thicken
It is actually for android models with navigationbar?Workwoman
T
1

you can use this sample code. it is dirty solution but it works

Thread t = new Thread(){
            public void run() {
                int y = mainScreenView.getHeight()-2;
                int x = 10;
                int counter = 0;
                int height = y;
                while (true){
                    final MotionEvent m = MotionEvent.obtain(
                            SystemClock.uptimeMillis(),
                            SystemClock.uptimeMillis(),
                            MotionEvent.ACTION_DOWN,
                            x, 
                            y,
                            INTERNAL_POINTER_META_STATE);
                    final MotionEvent m1 = MotionEvent.obtain(
                            SystemClock.uptimeMillis(),
                            SystemClock.uptimeMillis(),
                            MotionEvent.ACTION_UP,
                            x, 
                            y,
                            INTERNAL_POINTER_META_STATE);
                    boolean pointer_on_softkeyboard = false;
                    try {
                        getSingletonInstrumentation().sendPointerSync(m);
                        getSingletonInstrumentation().sendPointerSync(m1);
                    } catch (SecurityException e) {
                        pointer_on_softkeyboard = true;
                    }
                    if (!pointer_on_softkeyboard){
                        if (y == height){
                            if (counter++ < 100){
                                Thread.yield();
                                continue;
                            }
                        } else if (y > 0){
                            softkeyboard_height = mainScreenView.getHeight() - y;
                        }
                        break;
                    }
                    y--;

                }
                if (softkeyboard_height > 0 ){
                    // it is calculated and saved in softkeyboard_height
                } else {
                    calculated_keyboard_height = false;
                }
            }
        };
        t.start();
Thicken answered 12/3, 2012 at 15:21 Comment(3)
Where is INTERNAL_POINTER_META_STATE? metaState is referred to KeyEvent API: developer.android.com/reference/android/view/… but INTERNAL_POINTER_META_STATE is nowhere to be found.Achievement
INTERNAL_POINTER_META_STATE is just a id that identify this event sources. so you can track which pointer event are generated by you or by device. you should just set a integer value to INTERNAL_POINTER_META_STATEThicken
What is getSingletonInstrumentation() method?Encomiastic
D
1

This solution is also hacky but solve the problem (atleast for me).

  1. I have places on temporary view with transparent background at the bottom of the screen. So this view will be invisible.
  2. I have added android:windowSoftInputMode="adjustResize" flag in activity tag in manifest.
  3. Now main story is in onGlobalLayout(). There i calculate the difference between the y axis of temp view and height of root view

    final View view = findViewById(R.id.base); view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
    
        int rootViewHeight = view.getRootView().getHeight();
        View tv = findViewById(R.id.temp_view);
        int location[] = new int[2];
        tv.getLocationOnScreen(location);
        int height = (int) (location[1] + tv.getMeasuredHeight());
        deff = rootViewHeight - height;
        // deff is the height of soft keyboard
    
    }
    

    });

Diverticulitis answered 6/5, 2014 at 7:1 Comment(0)
V
1

If you don't want android:windowSoftInputMode="adjustResize" in your app. You can try something like this:

    any_view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            int height = main_layout.getHeight();
            Log.w("Foo", String.format("layout height: %d", height));
            Rect r = new Rect();
            main_layout.getWindowVisibleDisplayFrame(r);
            int visible = r.bottom - r.top;
            Log.w("Foo", String.format("visible height: %d", visible));
            Log.w("Foo", String.format("keyboard height: %d", height - visible));
        }
    });
Vitkun answered 16/7, 2015 at 15:22 Comment(1)
getWindowVisibleDisplayFrame doesnt work for me..it returns the Height of the ViewCollide
S
1

Let's suppose that the rootView of your layout is RelativeLayout. What you can do create a class CustomRelativeLayout which extends RelativeLayout and Overrides onSizeChanged Method inside it. So when the soft keyboard opens up, the height of the RelativeLayout will change and the change will be notified inside the onSizeChanged Method.

public class CustomRelativeLayout extends RelativeLayout {

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    int softKeyboardHeight = oldh - h; // Assuming softKeyboard Opened up
    // oldh is the height when the layout was covering the whole screen
    // h is the new height of the layout when the soft keyboard opened up

    if(softKeyboardHeight > oldh * 0.15) {
        Log.i("Here", Integer.toString(softKeyboardHeight));
        // Keyboard has popped up

    } else {
        // Not the keyboard
    }
}

In your Manifest file make these changes so that the Activity opens in Resize Mode and Not pan and scan mode. In Resize mode the Layout will be able to resize when keybaord opens up. To read more about pan-scan and Resize visit https://developer.android.com/training/keyboard-input/visibility

<activity
        android:name=".MainActivity"
        android:windowSoftInputMode="adjustResize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
Softfinned answered 24/4, 2019 at 19:10 Comment(0)
O
0

Try this

KeyboardView keyboardView = new KeyboardView(getApplicationContext(), null);
int height = (keyboardView.getKeyboard()).getHeight();
Toast.makeText(getApplicationContext(), height+"", Toast.LENGTH_LONG).show();
Overstride answered 8/9, 2014 at 16:33 Comment(3)
Looks so wonderful simple, just two lines of code... But it doesn't work for me keyboardView.getKeyboard() returns nullJaneejaneen
Same for me too ..keyboardView.getKeyboard() returns nullClaiborn
Might not be so accurate but if you don't need a listener its better to use this one.Zuber

© 2022 - 2024 — McMap. All rights reserved.