Android 获取PopupWindow宽高为0
一、环境
JDK8 + Android API23
二、问题
需要将PopupWindow展示在页面某个元素(假设为 sampleButton)的上方,所以 showAtLocation Y方向的值应该是 sampleButton.getTop() - popupWindow.getHeight()
但是打断点发现 getHeight 获取到值为0
三、解决
这是由于当元素不可见时,获取到的都是0,应该换种方式,使用**getMeasuredHeight()**获取真实高度
// 解决在View不可见时,直接getHeight为0的问题
int size[] = new int[2];
int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
popupWindow.getContentView().measure(width, height);
size[0] = popupWindow.getContentView().getMeasuredWidth();
size[1] = popupWindow.getContentView().getMeasuredHeight();