天天看点

Android上白鹭软键盘挡住输入框解决方案

最近在进行白鹭游戏的开发,发现了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