应用场景:当scrollView中嵌入一个ListView时,listview的高度不知道。显示时只显示一行。
自定义的ListView:
package com.hanju.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* 自定义ListView
*
* @author fan
*
*/
public class HJListView extends ListView {
public HJListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public HJListView(Context context, AttributeSet attrs) {
// TODO Auto-generated constructor stub
super(context, attrs);
}
public HJListView(Context context) {
// TODO Auto-generated constructor stub
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
测量方法:
// SetListViewHeight
public static void setHeight(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
int count = listAdapter.getCount();
for (int i = 0; i < count; i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight()
+ listView.getDividerHeight() / 2;
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
在setAdapter()后添加:
setHeight(mListView);