博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
PopupWindow计算弹出位置
阅读量:4704 次
发布时间:2019-06-10

本文共 2256 字,大约阅读时间需要 7 分钟。

1.首先自定义PopupWindow

   popWindowView= LinearLayout.inflate(context, R.layout.popupWindow,null);

   popupWindow = new PopupWindow(popWindowView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);

   popupWindow.setOutsideTouchable(true);//点击弹窗以外的地方消失

   popupWindow.setBackgroundDrawable(new BitmapDrawable());//响应返回键

2.一般我们会让弹出框在我们指定控件的某个位置展示,那么就有如下计算

             /**

* @param anchorView  弹窗时作为参照物的view     * @param contentView   内容布局(可以直接放popupWindow)     * @return 左上角的x,y坐标     */    private static int[] PopViewPos(final View anchorView, final View contentView) {        final int windowPos[] = new int[2];        final int anchorLoc[] = new int[2];     // 获取锚点View在屏幕上的左上角坐标位置,赋值给anchorLoc数组        anchorView.getLocationOnScreen(anchorLoc);         //获取参照view的高度        final int anchorHeight = anchorView.getHeight();        // 获取屏幕的高宽        final int screenHeight = ScreenUtils.getScreenHeight(anchorView.getContext());        final int screenWidth = ScreenUtils.getScreenWidth(anchorView.getContext());         //设置测量模式,让父容器不影响view的测量        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);        // 计算contentView的高宽        final int windowHeight = contentView.getMeasuredHeight();        final int windowWidth = contentView.getMeasuredWidth();        // 判断需要向上弹出还是向下弹出显示        final boolean isNeedShowUp = (screenHeight - anchorLoc[1] - anchorHeight < windowHeight);        if (isNeedShowUp) {            windowPos[0] = screenWidth - windowWidth;            windowPos[1] = anchorLoc[1] - windowHeight;        } else {            windowPos[0] = screenWidth - windowWidth;            windowPos[1] = anchorLoc[1] + anchorHeight;        }        return viewPos;    } 3.显示showAtLoaction int viewPos[] = calculatePopWindowPos(view, contentView); popupwindow.showAtLocation(view, Gravity.TOP | Gravity.START, viewPos[0], viewPos[1]);
 
/**     * 获取屏幕高度(px)     */    public static int getScreenHeight(Context context) {        return context.getResources().getDisplayMetrics().heightPixels;    }    /**     * 获取屏幕宽度(px)     */    public static int getScreenWidth(Context context) {        return context.getResources().getDisplayMetrics().widthPixels;    }
 

转载于:https://www.cnblogs.com/mrzha/p/8398486.html

你可能感兴趣的文章
配置NRPE的通讯
查看>>
匹配两个空格之间的字符。。。
查看>>
CSS 文字溢出 变成省略号 ...
查看>>
Spring事务
查看>>
java编程基础(三)流程控制语句
查看>>
让数据库跑的更快的7个MySQL优化建议
查看>>
jquery 取id模糊查询
查看>>
解决在vue中,自用mask模态框出来后,下层的元素依旧可以滑动的问题
查看>>
修改node节点名称
查看>>
PAT(B) 1014 福尔摩斯的约会(Java)
查看>>
PAT甲级题解-1123. Is It a Complete AVL Tree (30)-AVL树+满二叉树
查看>>
项目开发总结报告(GB8567——88)
查看>>
SSH加固
查看>>
端口扫描base
查看>>
iOS IM开发的一些开源、框架和教程等资料
查看>>
FansUnion:共同写博客计划终究还是“流产”了
查看>>
python 二维字典
查看>>
Arrays类学习笔记
查看>>
实验吧之【天下武功唯快不破】
查看>>
2019-3-25多线程的同步与互斥(互斥锁、条件变量、读写锁、自旋锁、信号量)...
查看>>