gpt4 book ai didi

android - 如何检测软件键盘在 Android 设备上是否可见?

转载 作者:IT老高 更新时间:2023-10-28 12:52:48 25 4
gpt4 key购买 nike

Android 中有没有办法检测软件(也称为“软”)键盘是否在屏幕上可见?

最佳答案

这对我有用。也许这始终是适用于所有版本的最佳方式。

设置一个键盘可见性属性并延迟观察这种变化会很有效,因为 onGlobalLayout 方法调用了很多次。另外最好检查一下设备旋转和 windowSoftInputMode 不是 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 - 如何检测软件键盘在 Android 设备上是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4745988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com