当前位置: 首页 > news >正文

Android PopupWindow弹窗动态显示在View的上下方,

序、周末不加班,

效果图如下。

我们要弹出的PopupWindow在View的下方,如果下方区域不够,则弹出在上方。

实现方案思路

我们在显示的时候,首先去计算一下弹窗高度。使用屏幕的高 - popupwind的高并且和popup的高做对比,如果大于的话,则显示在下方,如果小于的话,则显示在上方。

 /**** @param anchorView 锚点View* @param contentView 弹出的View* @return*/private int[] calculatePopWindowPos(final View anchorView, final View contentView) {final int[] windowPos = new int[2];final int[] anchorLoc = new int[2];// 获取锚点View在屏幕上的左上角坐标位置anchorView.getLocationOnScreen(anchorLoc);final int anchorHeight = anchorView.getHeight();// 获取屏幕的高宽final int screenHeight = getScreenHeight(anchorView.getContext());final int screenWidth = getScreenWidth(anchorView.getContext());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);Log.i("AAAA", "screenWidth = "+screenWidth+"---"+"windowWidth="+windowWidth);if (isNeedShowUp) {windowPos[0] = (screenWidth - windowWidth)/2;windowPos[1] = anchorLoc[1] - windowHeight;} else {windowPos[0] = (screenWidth - windowWidth)/2;windowPos[1] = anchorLoc[1] + anchorHeight;}return windowPos;}

显示popupwindow如下

 Button btn1 = findViewById(R.id.btn1);btn1.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {View contentView = LayoutInflater.from(ListActivity.this).inflate(R.layout.layout_window, null);PopupWindow popupWindow = new PopupWindow(contentView,ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.WRAP_CONTENT);// 设置PopupWindow可以获得焦点,否则无法响应点击事件popupWindow.setFocusable(true);
//                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));int[] windowPos = calculatePopWindowPos(view, contentView);// 3. 显示PopupWindowpopupWindow.showAtLocation(view,Gravity.TOP|Gravity.START, windowPos[0], windowPos[1]);}});

完毕。


http://www.mrgr.cn/news/12092.html

相关文章:

  • 8月27日cs61c
  • Redis6.0新特性
  • 在我的博士科研生活中,SCI的英语写作一直是我的挑战。
  • Vue3+Ts封装input组件时遇到的问题
  • 【iOS端】基于Uniapp跨平台接入即构RTC+相芯美颜
  • APP封装安装配置参考说明
  • swift自定义数据集微调Qwen-7B大模型,转换模型后使用ollama跑起来
  • AutoGPT开源项目解读
  • Halcon20.11深度学习语义分割模型
  • 数据结构概念
  • 使用hutool实现http的调用
  • Java中IO基础文本数据处理:BufferedReader 和 BufferedWriter
  • leetcode 76.最小覆盖子串
  • Python习题 154:用装饰器实现开始执行和结束执行时间
  • CVBS信号在视频应用中的角色与特性
  • C++中的智能指针介绍及使用
  • MIPI联盟D-PHYv1.2规范阅读笔记二之物理层接口协议PPI
  • AUTOSAR_EXP_ARAComAPI.pdf的第4章笔记
  • Docker 安装 Nginx
  • cv::resize 保留图片的二值性特点