如何在应用程序打开时获取键盘高度

ara*_*nna 2 keyboard android android-studio

我使用下面的代码来获取键盘高度。

view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @覆盖
            公共无效 onGlobalLayout() {
                矩形矩形 = 新矩形();
                view.getWindowVisibleDisplayFrame(rect);

                int screenHeight = view.getRootView().getHeight();
                int keyboardHeight = screenHeight - rect.bottom;
                如果(键盘高度!= 0){
                    如果(方向== Configuration.ORIENTATION_LANDSCAPE)
                        AppConfig.landscapeKeyboardHeight = keyboardHeight;
                    否则如果(方向== Configuration.ORIENTATION_PORTRAIT)
                        AppConfig.portraitKeyboardHeight = 键盘高度;
                }
            }
        });

但这仅在应用程序至少第一次打开键盘时才给出高度。我想要键盘的高度,甚至在它第一次打开之前。有没有办法做到这一点?提前致谢...

Sun*_*lly 5

之前我在获取键盘高度以显示一些对话框时遇到了同样的问题。您可以使用下面的方法来解决它。

rootView = getWindow().getDecorView().getRootView();
rootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            Rect rect = new Rect();
            rootView.getWindowVisibleDisplayFrame(rect);

            int screenHeight = rootView.getHeight();
            int keyboardHeight = screenHeight - (rect.bottom - rect.top);

            if(keyboardHeight > screenHeight / 3){
                keyboardActive = true;
                Log.d("Keyboard", "Active");

            }
            else{
                keyboardActive = false;
                Log.d("Keyboard", "Not Active");
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)