美文网首页
Android 点击输入框弹出键盘,布局随键盘往上移动

Android 点击输入框弹出键盘,布局随键盘往上移动

作者: hua_dm | 来源:发表于2019-03-13 09:39 被阅读0次

    一、效果图:

    1.正常登陆页面 2.布局随键盘往上移动的布局,登陆按钮不会被覆盖

    二、Code:

    /**

    *  1、获取main在窗体的可视区域

    *  2、获取main在窗体的不可视区域高度

    *  3、判断不可视区域高度,之前根据经验值,在有些手机上有点不大准,现改成屏幕整体高度的1/3

    *      1、大于屏幕整体高度的1/3:键盘显示  获取Scroll的窗体坐标

    *                          算出main需要滚动的高度,使scroll显示。

    *      2、小于屏幕整体高度的1/3:键盘隐藏

    *

    * @param main 根布局 

    * @param scroll 需要显示的最下方View

    */

    public static 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);

    }

    }

    });

    }

    三、调用方式:

    在Activity的onCreate()中调用,

    一句话搞定

    仅此记录。

    相关文章

      网友评论

          本文标题:Android 点击输入框弹出键盘,布局随键盘往上移动

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