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();