美文网首页
完美解决键盘遮挡底部view的方案以及键盘的监听弹出收起

完美解决键盘遮挡底部view的方案以及键盘的监听弹出收起

作者: mercuryli | 来源:发表于2019-08-13 16:07 被阅读0次

日语键盘在输入字的时候键盘会再弹起一个文字选择框,导致底部的view会遮挡一部分.

public void addLayoutListener(final View main, final View scroll) {
    main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
/* possiblyResizeChildOfContent();
            Rect rect = new Rect();
            main.getWindowVisibleDisplayFrame(rect);
            int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;

            if (mainInvisibleHeight > 180) {
                int[] location = new int[2];
                scroll.getLocationInWindow(location);//获取其当前位置
                int scrollHeight = (location[1] + scroll.getHeight() + ((ConstraintLayout.LayoutParams) scroll.getLayoutParams()).bottomMargin) - rect.bottom;
                if (scrollHeight > 0) {
                    main.scrollTo(0, scrollHeight);

                }
            } else {
                main.scrollTo(0, 0);
            }*/

            int usableHeightNow = computeUsableHeight(main);
            if (usableHeightNow != usableHeightPrevious) {
                int usableHeightSansKeyboard = layout.getRootView().getHeight();
                int heightDifference = usableHeightSansKeyboard - usableHeightNow;
                int scrollHeight = scroll.getHeight() + ((ConstraintLayout.LayoutParams) scroll.getLayoutParams()).bottomMargin;
                if (heightDifference > (usableHeightSansKeyboard / 4)) {
                    // 键盘弹出
                    main.scrollTo(0, heightDifference-scrollHeight);

                } else {
                    // 键盘收起
                   main.scrollTo(0,0);
                }
                if(heightDifference<50 && heightDifference>0){
                    main.scrollTo(0,heightDifference);
                }

                layout.requestLayout();
                usableHeightPrevious = usableHeightNow;
            }
        }
    });
}

view 是当前页面最外层的view ,Scroll是你不想不想遮挡的底部View

private int computeUsableHeight(View main) {
    Rect r = new Rect();
    main.getWindowVisibleDisplayFrame(r);
    return (r.bottom - r.top);
} 

activity 设置为 android:windowSoftInputMode="adjustPan"

我的scroll是在最底部,经测试是没问题的。
参考1
参考2

相关文章

网友评论

      本文标题:完美解决键盘遮挡底部view的方案以及键盘的监听弹出收起

      本文链接:https://www.haomeiwen.com/subject/zurbjctx.html