最近在進行白鹭遊戲的開發,發現了Android上的一個坑:就是在遊戲界面内,輸入框會被彈出來的軟鍵盤擋住而不會上移。經過查閱資料,通過如下方式可以解決:
- Android原生部分代碼:
public class AndroidBug5497Workaround {
// For more information, see https://code.google.com/p/android/issues/detail?id=5497
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
public static void assistActivity (Activity activity) {
new AndroidBug5497Workaround(activity);
}
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private AndroidBug5497Workaround(Activity activity) {
FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard/4)) {
// keyboard probably just became visible
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {
// keyboard probably just became hidden
frameLayoutParams.height = usableHeightSansKeyboard;
}
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return (r.bottom - r.top);// 全屏模式下: return r.bottom
}
}
在相應的activity的oncreate函數中執行,放在setContentView後面:
AndroidBug5497Workaround.assistActivity(this);
- H5部分代碼:
if (/Android/gi.test(navigator.userAgent)) {
// 檢測userAgent是否為Android
window.addEventListener('resize', function () {
if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') {
// 判斷目前active的元素是否為input/ textarea
window.setTimeout(function () {
document.activeElement.scrollIntoViewIfNeeded()
// 原生方法,滾動至需要顯示的位置
}, 0)
}
})
}
這段代碼放在game.html的js部分代碼中即可。(game.html是本地加載的首頁代碼)
在這裡特意做一個記錄,以備查閱。
https://www.diycode.cc/topics/383
https://www.jianshu.com/p/baa539ae97b6