我已使用以下代码获取键盘高度。
view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); view.getWindowVisibleDisplayFrame(rect); int screenHeight = view.getRootView().getHeight(); int keyboardHeight = screenHeight - rect.bottom; if(keyboardHeight != 0){ if(orientation == Configuration.ORIENTATION_LANDSCAPE) AppConfig.landscapeKeyboardHeight = keyboardHeight; else if(orientation == Configuration.ORIENTATION_PORTRAIT) AppConfig.portraitKeyboardHeight = keyboardHeight; } } });
但这只有在应用程序首次打开键盘时才会显示高度。键盘的高度即使在它第一次打开之前也是如此。有没有办法做到这一点?提前谢谢......
答案 0 :(得分:4)
我在获取显示某些对话框的键盘高度之前遇到了同样的问题。您可以使用以下方法解决它。
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");
}
}
});