解决EditText 被部分遮挡的问题

1.首先在布局文件最外层加scrollview

2.代码中使用如下方法

private void controlKeyboardLayout(final ScrollView root, final Activity context) {
    root.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
        Rect rect = new Rect();
        root.getWindowVisibleDisplayFrame(rect);
        int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
        //若不可视区域高度大于100,则键盘显示
        if (rootInvisibleHeight > 100) {
            int[] location = new int[2];
            View focus = context.getCurrentFocus();
            if (focus != null) {
                focus.getLocationInWindow(location);
                int scrollHeight = (location[1] + focus.getHeight()) - rect.bottom;
                if (rect.bottom < location[1] + focus.getHeight()) {
                    root.scrollTo(0, scrollHeight);
                }
            }
        } else {
            //键盘隐藏
            root.scrollTo(0, 0);
        }
    });
}

你可能感兴趣的:(解决EditText 被部分遮挡的问题)