早就想写博客了,直到今天才开始真正的去写一篇,接下来奉上今天的主题:实现PopupWindow跟随ProgressBar进度显示
最近遇到一个功能实现,大概就是以下这个图的样子,上方为PopupWindow,下方有ProgressBar,PopupWindow位置跟随ProgressBar进度位置动态变化
开始实现吧:
首先实例化PopupWindow
pop_wiew = LayoutInflater.from(this).inflate(R.layout.member_popwindow, null, false);
mPopupWindow = new PopupWindow(pop_wiew, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
然后去测量PopupWindow的宽高,因为放置位置为PopupWindow的中央:
pop_wiew.post(new Runnable() { @Override public void run() { pop_wiew.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); popwidth = pop_wiew.getMeasuredWidth(); pophight = pop_wiew.getMeasuredHeight(); } });因为绘画过程异步,所以使用view的post方法,携带自身宽高属性以供获得,需要注意的是:
pop_wiew.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);若是不设置测量模式,则获取不到PopupWindow的属性(已踩过坑)
另外需要注意的是,如果不做任何操作,这样直接显示PopupWindow,会导致界面的控件获取不到焦点,并且返回键失效(仅针对上图实现的功能来说),所以需要做如下操作:
mPopupWindow.setTouchable(true); mPopupWindow.setFocusable(false); mPopupWindow.setOutsideTouchable(false);接下来是对Progress进行操作:
mProbarLeftMembercenterExpeience.post(new Runnable() { @Override public void run() { int width = mProbarLeftMembercenterExpeience.getWidth(); int height = mProbarLeftMembercenterExpeience.getHeight(); int[] location = new int[2]; mProbarLeftMembercenterExpeience.getLocationOnScreen(location); //获得在屏幕中的x,y值 int x = location[0]; int y = location[1]; //目前popwindow应该在的x值 int poplocation = (int) (width * baifenbi + x); mPopupWindow.showAtLocation(mProbarLeftMembercenterExpeience, Gravity.NO_GRAVITY, poplocation - popwidth / 2, y - pophight - height); } });同理,使用view的post方法获得自己的属性,然后首先获取自身的宽高:
int width = mProbarLeftMembercenterExpeience.getWidth(); int height = mProbarLeftMembercenterExpeience.getHeight();然后获得在屏幕中的x,y值:
int[] location = new int[2]; mProbarLeftMembercenterExpeience.getLocationOnScreen(location); //获得在屏幕中的x,y值 int x = location[0]; int y = location[1];最后设置popwindow的位置:
int poplocation = (int) (width * percentage+ x); mPopupWindow.showAtLocation(mProbarLeftMembercenterExpeience, Gravity.NO_GRAVITY, poplocation - popwidth / 2, y - pophight - height);上述代码中的percentage为ProgressBar的当前百分比,至于PopupWindow在何处显示,请看管自行百度。
人生第一遍博客,如有错误,请指出,谢谢观看!