日常开发经常碰到这种问题,界面中输入框下面有提交按钮,输入后才能点击提交,但是当我们点击输入框时,会弹起软键盘,当我们输入完内容后,无法直接点击按钮,因为被软键盘挡住了,只能将软键盘关掉才能点击按钮,增加了用户多余的动作,不太友好。

          我们可以想个办法当软键盘显示时,让按钮滑到软键盘之上,让我们不关掉软键盘也能点击输入框下面的按钮:

   /**
     * 设置键盘不遮挡按钮
     * @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 mainInvisibleHeight = main.getRootView().getHeight() - rect.bottom;
                if (mainInvisibleHeight > 100) {
                    int[] location = new int[2];
                    scroll.getLocationInWindow(location);
                    int srollHeight = (location[1] + scroll.getHeight()) - rect.bottom;
                    if (isKeyboardShown(main)) {
                        main.scrollTo(0, srollHeight);
                    } else {
                        main.scrollTo(0, 0);
                    }
                }else{
                    main.scrollTo(0, 0);
                }
            }
        });
    }

    /**
     *判断软键盘是否弹起
     *
    */
    public static boolean isKeyboardShown(View rootView) {
        try {
            final int softKeyboardHeight = 120;
            Rect r = new Rect();
            rootView.getWindowVisibleDisplayFrame(r);
            DisplayMetrics dm = rootView.getResources().getDisplayMetrics();
            int heightDiff = rootView.getBottom() - r.bottom;
            return heightDiff > softKeyboardHeight * dm.density;
        } catch (Exception e) {
            return false;
        }
    }

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐