android 实现按钮浮动在键盘上方的实例代码
大家好,我是梦辛工作室的灵,最近在帮客户修改安卓程序时,有要求到一个按钮要浮动在键盘的上方,下面大概讲一下实现方法:
其实很简单,分三步走
第一步获取当前屏幕的高度
DisplaydefaultDisplay=mcontext.getWindowManager().getDefaultDisplay(); Pointpoint=newPoint(); defaultDisplay.getSize(point); height=point.y;
第二步获取当前屏幕可见区域的高度,用于判断当前键盘是否隐藏或显示
publicvoidsetFloatView(Viewroot,Viewfloatview){
this.root=root;//根节点
listener=newViewTreeObserver.OnGlobalLayoutListener(){
@Override
publicvoidonGlobalLayout(){
Rectr=newRect();
mcontext.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
intheightDifference=height-(r.bottom-r.top);//实际高度减去可视图高度即是键盘高度
booleanisKeyboardShowing=heightDifference>height/3;
if(isKeyboardShowing){
//键盘显示
}else{
//键盘隐藏
}
}
};
root.getViewTreeObserver().addOnGlobalLayoutListener(listener);
}
第三步当键盘隐藏时让按钮动画移动至原有位置,当前键盘显示时让按钮动画移动至当前键盘的高度上方
if(isKeyboardShowing){
//键盘显示
floatview.animate().translationY(-heightDifference).setDuration(0).start();
}else{
//键盘隐藏
floatview.animate().translationY(0).start();
}
然后我为了方便封装了一个工具类FloatBtnUtil,很好用,下面是代码
/**
*梦辛灵实现按钮浮动工具
*/
publicclassFloatBtnUtil{
privatestaticintheight=0;
privateActivitymcontext;
privateViewTreeObserver.OnGlobalLayoutListenerlistener;
privateViewroot;
publicFloatBtnUtil(Activitymcontext){
this.mcontext=mcontext;
if(height==0){
DisplaydefaultDisplay=mcontext.getWindowManager().getDefaultDisplay();
Pointpoint=newPoint();
defaultDisplay.getSize(point);
height=point.y;
}
}
publicvoidsetFloatView(Viewroot,Viewfloatview){
this.root=root;//视图根节点floatview//需要显示在键盘上的View组件
listener=newViewTreeObserver.OnGlobalLayoutListener(){
@Override
publicvoidonGlobalLayout(){
Rectr=newRect();
mcontext.getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
intheightDifference=height-(r.bottom-r.top);
booleanisKeyboardShowing=heightDifference>height/3;
if(isKeyboardShowing){
floatview.animate().translationY(-heightDifference).setDuration(0).start();
}else{
floatview.animate().translationY(0).start();
}
}
};
root.getViewTreeObserver().addOnGlobalLayoutListener(listener);
}
publicvoidclearFloatView(){
if(listener!=null&&root!=null)
root.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
}
}
下面是使用代码:
privatevoidinitFloatBtn(){
FloatBtnUtilfloatBtnUtil=newFloatBtnUtil(this);
LinearLayoutlin_bottom=(LinearLayout)this.findViewById(R.id.lin_bottom);
LinearLayoutlin_root=(LinearLayout)this.findViewById(R.id.lin_root);
floatBtnUtil.setFloatView(lin_root,lin_bottom);
}
总结
到此这篇关于android实现按钮浮动在键盘上方的文章就介绍到这了,更多相关android实现按钮浮动在键盘上方内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!