我有Listview根据评论长度有评论列表,每行的高度不同。我想以编程方式为listview提供高度。我试图获得每一行的高度,但每次我为每一行获得相同的高度..但每行根据其内容具有不同的大小。我使用了以下代码:
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter != null) {
int numberOfItems = listAdapter.getCount();
// Get total height of all items.
int totalItemsHeight = 0;
for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
View item = listAdapter.getView(itemPos, null, listView);
item.measure(0, View.MeasureSpec.UNSPECIFIED);
totalItemsHeight += item.getMeasuredHeight();
Log.e("HEIGHT", "" + item.getMeasuredHeight());
}
// Get total height of all item dividers.
int totalDividersHeight = listView.getDividerHeight() *
(numberOfItems - 1);
// Set list height.
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalItemsHeight + totalDividersHeight;
listView.setLayoutParams(params);
listView.requestLayout();
}
答案 0 :(得分:0)
你必须等待它的布局和测量。
如果您想强制它为包装内容的项目提前做到这一点,您可以调用这样的度量:
item.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST));
在致电getMeasuredHeight
之前。但请记住,这将返回像素而不是dp,因此您可能需要进行一些转换。
答案 1 :(得分:0)
尝试使用ViewTreeObserver:
int mViewHeight =WindowManager.LayoutParams.WRAP_CONTENT;
callAddOnGlobalLayoutListner(item);
Method ::
public void callAddOnGlobalLayoutListener(final View v){
view.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
// TODO Auto-generated method stub
v.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
mViewHeight = view.getMeasuredHeight();
Log.d("Height",mViewHeight+"");
}
}
});
}