Search code examples
androidandroid-fragmentsvirtual-keyboard

Get Soft Keyboard Height in fragment


I have a fragment that contains 20+ rows for adding personal info. The exact number of rows depends of how much an employer wants from the users of the app.

If the number of rows I need to show is bigger than the available space, with soft keyboard showing, I have to move the other rows to the next screen, and so on.

This was my gameplan: Check how high my rows are + margins (easy, hardcoded) Check the total screen height Check the soft keyboard height

That would give me enough info to calculate... you'll get the picture :)

There didn't seem to be something like "getSoftKeyboardHeight", so I used this code in my fragment:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        root = getActivity().getWindow().getDecorView().findViewById(R.id.fragment_container);

        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public void onGlobalLayout() {
                int heightDiff = root.getRootView().getHeight() - root.getHeight();
                // IF height diff is more then 150, consider keyboard as visible.
                Log.d("slideactivity", "total " + root.getRootView().getHeight());
                Log.d("slideactivity", "total " + root.getHeight());
                Log.d("slideactivity", "heightdiff = " + heightDiff);
            }
        });
    }

Log output:

08-13 12:37:55.242     D/slideactivity﹕ total 600
08-13 12:37:55.242     D/slideactivity﹕ total 543
08-13 12:37:55.242     D/slideactivity﹕ heightdiff = 57

While actually half my screen is taken up by the soft keyboard. I started to wonder.. maybe the keyboard is just popping up when the values get printed, so I didn't get a correct read.. I used a hacky Thread.Sleep in an async task before measuring, but the same info came up.

Does anyone know how to fix this problem? Maybe there is some library that does all the work? Or I'm looking for solutions in the wrong places?

Any help is very much appreciated, since I already checked a lot of stackoverflow answers!


Solution

  • I finally found a solution. The reason why this didn't work out is because I didn't place my content in a ScrollView element. By doing this, the softkeyboard pushes the layout, hence creating a difference in height, that can be measured.