我一直在研究如何做到这一点,尽管问题已经得到了回答,但我想提供一个我认为更好的解决方案:
查看ListView的源代码,您可以在onMeasure(...)代码中看到以下内容:
if (heightMode == MeasureSpec.AT_MOST) {
// TODO: after first layout we should maybe start at the first visible position, not 0
heightSize = measureHeightOfChildren(widthMeasureSpec, 0, NO_POSITION, heightSize, -1);
}
所以只需调用listView的measure方法,并将高度参数传递为MeasureSpec.AT_MOST,而不是通常的MeasureSpec.UNSPECIFIED。
我使用以下代码来测量ListView并将其放置在弹出窗口中:
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(displayMetrics.widthPixels, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(displayMetrics.heightPixels, MeasureSpec.AT_MOST);
mCatalogView.measure(widthMeasureSpec, heightMeasureSpec);
mPopup.setWidth(mCatalogView.getMeasuredWidth());
mPopup.setHeight(mCatalogView.getMeasuredHeight());