解决软键盘遮挡问题(指定控件上移)

ViewTreeObserver.OnGlobalLayoutListener mListener;
    ViewTreeObserver mTreeObserver;
    /**
     * 移动的布局
     * @param root     需要移动的布局
     * @param button   最底部的布局
     */
    private void buttonBeyondKeyboardLayout(final  View root,final View button) {

        mListener = new ViewTreeObserver.OnGlobalLayoutListener() {

            private int mButtonHeight;

            @Override
            public void onGlobalLayout() {
                Log.e("测试", "-------统计测量------" );
                Log.d(TAG, "BaseApplication.screenHeight:" + BaseApplication.screenHeight);
                Rect rect = new Rect();
                // 获取的是设备屏幕大小, 因为有虚拟键的存在所以取窗口实际大小
//                int rootInvisibleHeight = getWindow().getDecorView().getHeight() - rect.bottom;
                // 获得当前窗口的可视区域的大小
                getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
                // 当前窗口的高度 - 可见区域的底部 = 不可见窗体的大小[即软件盘的高度]
                int rootInvisibleHeight = BaseApplication.screenHeight - rect.bottom;

                // 事件为弹出软键盘时,软件盘至少有100px吧 这里100可以替换为软件盘的高度
                if (rootInvisibleHeight > 100) {
                    int[] location = new int[2];
                    // 获得按钮即所要检测的视图的高
                    button.getLocationInWindow(location);
                    // 按钮的底部------
                    int buttonHeight = button.getHeight() + location[1];
                    // **************  判断是否需要进行移动 **************
                    if (rect.bottom > buttonHeight) {
                        // 如果不需要移动那么直接移除
                        if (mListener != null && mTreeObserver.isAlive()) {
                            mTreeObserver.removeOnGlobalLayoutListener(this);
                        }
                        mListener = null;
                    } else {
                        // 计算向上移动的高度
//                        mButtonHeight = (buttonHeight - rect.bottom + dpToPx(20));
                        mButtonHeight = (buttonHeight - rect.bottom + 20);
                        Log.e("软键盘", "onGlobalLayout:   = "+ mButtonHeight);
                        // 注意scroll,移动的是内容
                        root.scrollTo(0, mButtonHeight);
                    }
                } else {
                    // 软键盘隐藏进行还原
                    root.scrollTo(0, 0);
                }
            }
        };
        mTreeObserver = root.getViewTreeObserver();
        mTreeObserver.addOnGlobalLayoutListener(mListener);
    }
发布了30 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_36029400/article/details/85317505