软键盘顶出EditView的组件

一,简介
软键盘顶出布局下的EditView组件,在最后的EditView下,使得软键盘不要覆盖到其中的EditView


二,代码
布局--软键盘在Button按钮之下

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mainlayout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout >
<EditView/>
<EditView/>
<EditView/>
</RelativeLayout >
<Button/>
</RelativeLayout >

实现

    @BindView(R.id.mainlayout)
    PercentRelativeLayout percentRelativeLayout;
//监听软键盘
        addLayoutListener(percentRelativeLayout, btn);
  /**
     *  1、获取main在窗体的可视区域
     *  2、获取main在窗体的不可视区域高度
     *  3、判断不可视区域高度,之前根据经验值,在有些手机上有点不大准,现改成屏幕整体高度的1/3
     *      1、大于屏幕整体高度的1/3:键盘显示  获取Scroll的窗体坐标
     *                           算出main需要滚动的高度,使scroll显示。
     *      2、小于屏幕整体高度的1/3:键盘隐藏
     *
     * @param main 根布局
     * @param scroll 需要显示的最下方View
     */
    public void addLayoutListener(final View main, final View scroll) {
        main.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                main.getWindowVisibleDisplayFrame(rect);
                int screenHeight = main.getRootView().getHeight();
                int mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
                if (mainInvisibleHeight > screenHeight / 4) {
                    int[] location = new int[2];
                    scroll.getLocationInWindow(location);
                    int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                    main.scrollTo(0, srollHeight);
                } else {
                    main.scrollTo(0, 0);
                }
            }
        });
    }


猜你喜欢

转载自blog.csdn.net/qwer492915298/article/details/88552231