解决软键盘弹出遮挡button

在一般登录界面,软键盘弹出时会遮挡登录按钮,网上的解决方法一般都是设置WindowSoftInputMode和scrollview嵌套,但无法达到我想要的效果。

下面这种方法能够解决:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
        addLayoutListener(rootView, bottomView);
    }
    /**
     * @param rootView 根布局
     * @param bottomView 需要显示的最下方View,
     */
    public void addLayoutListener(View rootView, View bottomView) {
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            Rect rect = new Rect();
            rootView.getWindowVisibleDisplayFrame(rect);//获取rootView的可视区域
            int invisibleHeight = rootView.getRootView().getHeight() - rect.bottom;//获取rootView的不可视区域高度
            if (invisibleHeight > 150) { //键盘显示 
                int[] location = new int[2];
                bottomView.getLocationInWindow(location); //获取bottomView的坐标
                int scrollHeight = (location[1] + bottomView.getHeight()) - rect.bottom;//算出需要滚动的高度
                if (scrollHeight != 0) {//防止界面元素改变调用监听,使界面上下跳动,如验证码倒计时
                    rootView.scrollTo(0, scrollHeight);
                }
            } else {
                rootView.scrollTo(0, 0);
            }
        });
    }
    原文作者:白色相簿
    原文地址: https://www.jianshu.com/p/733759fd87bf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞