我的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();
}
您必须等待布置并测量它。
如果您想强迫它提早进行此操作,以包装内容,可以这样称呼:
item.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST));
致电getMeasuredHeight
之前。但是请记住,这将返回像素不是DP,因此您可能需要进行一些转换。
尝试使用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+"");
}
}
});
}