防止界面被输入法遮挡

2018-01-27  本文已影响0人  附庸风雅_
    /**
     * rootHeight是window的高
     * rectBottom是window的Y坐标
     * mainInvisibleHeight是window的Y轴被遮挡的高度
     * needScrollHeight是需要滑动的距离(小于0代表下滑,大于0代码上滑)
     * 本方法认为输入法的占屏比会超过1/5
     *
     * @param view   layout(可以是当前布局的任意控件或layout)
     * @param scroll 要求不被遮挡的控件
     */
    private void addLayoutListener(final View view, final View scroll) {
        view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取window的可视区域大小,并set到rect对象中
                view.getWindowVisibleDisplayFrame(rect);
                int rootHeight = view.getRootView().getHeight();
                int rectBottom = rect.bottom;
                int mainInvisibleHeight = rootHeight - rectBottom;
                if (mainInvisibleHeight > rootHeight/5) {
                    int[] location = new int[2];
                    scroll.getLocationInWindow(location);
                    int scrollHeight = scroll.getHeight();
                    int locations = location[1];
                    int needScrollHeight = (locations + scrollHeight) - rectBottom;
                    if (needScrollHeight > 0) {
                        view.scrollTo(0, needScrollHeight);
                    }
                } else {
                    view.scrollTo(0, 0);
                }
            }
        });
    }

这是一段防止界面被遮挡的代码,原理是动态移动被遮挡控件位置

上一篇 下一篇

猜你喜欢

热点阅读