天天看点

安卓popupWindow高度设置为WRAP_CONTENT时获取高度

背景

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

安卓popupWindow高度设置为WRAP_CONTENT时获取高度

问题原因

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

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

期待效果

默认在菜品下方展示,展示不开时,在菜品上方展示。

安卓popupWindow高度设置为WRAP_CONTENT时获取高度

解决方案

正确的方法获取高度的方法是创建之后调用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());