PopupWindow位置
16lz
2021-01-25
Android中PopupWindow位置的确定一般通过showAsDropDown函数来实现,该函数有两个重载函数,分别定义如下:
Java代码
- publicvoidshowAsDropDown(Viewanchor){
- showAsDropDown(anchor,0,0);
- }
- publicvoidshowAsDropDown(Viewanchor,intxoff,intyoff){
- if(isShowing()||mContentView==null){
- return;
- }
- registerForScrollChanged(anchor,xoff,yoff);
- mIsShowing=true;
- mIsDropdown=true;
- WindowManager.LayoutParamsp=createPopupLayout(anchor.getWindowToken());
- preparePopup(p);
- updateAboveAnchor(findDropDownPosition(anchor,p,xoff,yoff));
- if(mHeightMode<0)p.height=mLastHeight=mHeightMode;
- if(mWidthMode<0)p.width=mLastWidth=mWidthMode;
- p.windowAnimations=computeAnimationResource();
- invokePopup(p);
- }
也就是说,调用第一个函数时,x和y坐标偏移量默认是0,此时PopupWindow显示的结果如下中图所示。而要实现PopupWindow显示在wenwen的正下方时,就需要程序员自己进行坐标偏移量的计算,下右图所示,当点击wenwen时,PopupWindow显示在正下方,这正是我们所需要的,对称是一种美啊。
代码实现的关键是点击wenwen后的响应函数,此处直接上代码,不废话了:
Java代码
- publicvoidonClick(Viewv){
- LayoutInflatermLayoutInflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
- ViewGroupmenuView=(ViewGroup)mLayoutInflater.inflate(
- R.layout.tips,null,true);
- pw=newPopupWindow(menuView,LayoutParams.WRAP_CONTENT,
- LayoutParams.WRAP_CONTENT,true);
- //设置点击返回键使其消失,且不影响背景,此时setOutsideTouchable函数即使设置为false
- //点击PopupWindow外的屏幕,PopupWindow依然会消失;相反,如果不设置BackgroundDrawable
- //则点击返回键PopupWindow不会消失,同时,即时setOutsideTouchable设置为true
- //点击PopupWindow外的屏幕,PopupWindow依然不会消失
- pw.setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));
- pw.setOutsideTouchable(false);//设置是否允许在外点击使其消失,到底有用没?
- pw.setAnimationStyle(R.style.PopupAnimation);//设置动画
- //计算x轴方向的偏移量,使得PopupWindow在Title的正下方显示,此处的单位是pixels
- intxoffInPixels=ScreenTools.getInstance(PopDemoActivity.this).getWidth()/2-titleName.getWidth()/2;
- //将pixels转为dip
- intxoffInDip=ScreenTools.getInstance(PopDemoActivity.this).px2dip(xoffInPixels);
- pw.showAsDropDown(titleName,-xoffInDip,0);
- //pw.showAsDropDown(titleName);
- pw.update();
- TextViewtv=(TextView)menuView.findViewById(R.id.tips_ok);
- tv.setOnClickListener(newView.OnClickListener(){
- publicvoidonClick(Viewv){
- pw.dismiss();
- }
- });
- }
更多相关文章
- 没有一行代码,「2020 新冠肺炎记忆」这个项目却登上了 GitHub 中
- Android(安卓)Studio 设置内存大小及原理
- AlertDialog使用自定义的布局
- android javascript 调用activity
- java.io.IOException:Can't read [F:\..\android-support-v4.ja
- android之解析包时出现错误(二)
- android之点击回退键俩次退出程序
- Android之Handler的post注意事项
- 基于rk3288平台android5.1系统的wifi流程分析 ---- 打开wifi,扫描