本文介绍了如何检测软件键盘在 Android 设备上是否可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Android 中是否有办法检测软件(也称为软")键盘是否在屏幕上可见?
Is there a way in Android to detect if the software (a.k.a. "soft") keyboard is visible on screen?
推荐答案
这对我有用.也许这始终是所有版本的最佳方式.
This works for me. Maybe this is always the best way for all versions.
设置键盘可见性的属性并延迟观察此更改将是有效的,因为 onGlobalLayout 方法调用了多次.检查设备旋转也很好,windowSoftInputMode
不是 adjustNothing
.
It would be effective to make a property of keyboard visibility and observe this changes delayed because the onGlobalLayout method calls many times. Also it is good to check the device rotation and windowSoftInputMode
is not adjustNothing
.
boolean isKeyboardShowing = false;
void onKeyboardVisibilityChanged(boolean opened) {
print("keyboard " + opened);
}
// ContentView is the root view of the layout of this activity/fragment
contentView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
Rect r = new Rect();
contentView.getWindowVisibleDisplayFrame(r);
int screenHeight = contentView.getRootView().getHeight();
// r.bottom is the position above soft keypad or device button.
// if keypad is shown, the r.bottom is smaller than that before.
int keypadHeight = screenHeight - r.bottom;
Log.d(TAG, "keypadHeight = " + keypadHeight);
if (keypadHeight > screenHeight * 0.15) { // 0.15 ratio is perhaps enough to determine keypad height.
// keyboard is opened
if (!isKeyboardShowing) {
isKeyboardShowing = true
onKeyboardVisibilityChanged(true)
}
}
else {
// keyboard is closed
if (isKeyboardShowing) {
isKeyboardShowing = false
onKeyboardVisibilityChanged(false)
}
}
}
});
这篇关于如何检测软件键盘在 Android 设备上是否可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!