事实上,正如 @user2493245 所说,这是一个众所周知的错误。但我找到了一个解决方法,至少就我的具体情况而言。
在 WebView 上,只需检查视图可见区域的坐标。
final View activityRootView = this.root;
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
Rect r = new Rect();
//r will be populated with the coordinates of your view that area still visible.
activityRootView.getWindowVisibleDisplayFrame(r);
int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
if(heightDiff != lastValue) {
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
appView.sendJavascript("onKeyBoardShow(" + r.bottom + ");");
} else {
appView.sendJavascript("onKeyBoardHide();");
}
lastValue = heightDiff;
}
}
});
如您所见,我将该信息发送到 WebView。在 HTML 上,我有两种方法来处理这个问题:
function onKeyBoardShow(bottom) {
var diff = ($('input[type=text]:focus').offset().top - bottom) + 50;
if(diff > 0) {
$('body').css("top", (diff * -1) + "px");
}
};
function onKeyBoardHide() {
$('body').css("top", "0px");
};
基本上,onKeyBoardShow 会聚焦输入字段并计算移动主体所需的像素数量,从而允许用户看到输入字段。 onKeyBoardHide,只需将主体置于其原始位置即可。
PS:这仅在视口以 devicedpi 为目标时起作用,因为我们需要修改获取有关设备 dpi 的 diff 的方式。
PS2:第一部分代码不是我的,我只是为了满足我的需要而编辑的。我在一个问题上看到了这一点,但不幸的是现在我找不到它。如果我找到它,我会在这里发布链接。