Android输入法键盘上方增加view悬浮组件

 

public class FloatBtnUtil {

    private static  int height = 0;
    private Activity mcontext;
    private ViewTreeObserver.OnGlobalLayoutListener listener;
    private View root;
    private ViewTreeObserver.OnGlobalLayoutListener mListener;
    private int distanceY;
    private ViewTreeObserver mTreeObserver;
    private ValueAnimator mValueAnimator;

    public FloatBtnUtil(Activity mcontext){
        this.mcontext = mcontext;
        if (height == 0){
            Display defaultDisplay = mcontext.getWindowManager().getDefaultDisplay();
            Point point = new Point();
            defaultDisplay.getSize(point);
            height = point.y;
        }
    }

    /**
     * @param root 视图根节点
     * @param floatview 需要显示在键盘上的View组件
     */
    public void setFloatView(View root,View floatview){
        this.root = root;	
        listener =  new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                mcontext.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
                int heightDifference = height - (r.bottom - r.top);
                boolean isKeyboardShowing = heightDifference > height / 3;
                if(isKeyboardShowing){
                    floatview.setVisibility(View.VISIBLE);
                    root.scrollTo(0, heightDifference+floatview.getHeight());
                }else{
                    root.scrollTo(0, 0);
                    floatview.setVisibility(View.GONE);
                }
            }
        };
        root.getViewTreeObserver().addOnGlobalLayoutListener(listener);
    }

    public void clearFloatView(){
        if (listener != null && root != null) {
            root.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
        }
    }

}
工具类用法:
floatBtnUtil = new FloatBtnUtil(this);
floatBtnUtil.setFloatView(findViewById(R.id.root_view), flFloat);

原理:键盘弹出时,计算键盘高度,并将布局向上滚动键盘高度的距离,如果其他布局外层没有嵌套scrollView,就平移view组件距离

遇到问题:

1.需要显示在键盘上的View组件刚开始位置不对,要不在键盘上方有段距离,要不被键盘遮挡,最后操作是把view组件放在布局最下面,键盘没展示时view组件时被其他布局顶出去的

2.如果有其他editView不需要展示这个组件,可以添加下行代码取消对键盘的监听

floatBtnUtil.clearFloatView();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值