背景

选择多规格菜品时,会使用popupWindow在菜品下方弹出待选择的规格。popupWindow支持下方展示不开时,自动移到上方展示,但实际并没有,而是下方被遮盖。

{6344BD44-E946-452A-A287-15B400972278}_20190912100229.jpg

问题原因

popupWindow在创建时未声明高度,而是根据数据动态渲染内容,高度也是动态的。

PopupWindow在创建时宽度高度设置为match_parent或者wrap_content时,通过getWidth、getHeight或者getContentView.getMeasuredWidth、getContentView.getMeasuredHeight 不能获取到真实的高度!

期待效果

默认在菜品下方展示,展示不开时,在菜品上方展示。
{2A720588-5F33-48FA-9D28-F3F8439C1186}_20190912100248.jpg

解决方案

正确的方法获取高度的方法是创建之后调用measure方法对View进行测量,然后获取宽度与高度!popupWindow有了高度后,就会正常展示。

final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

popupWindow.setHeight(popupWindow.getContentView().getMeasuredHeight());
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐