第一种方法:
重写Listview的onMeasure方法
public class ChildListView extends ListView {
public ChildListView(Context context) {
super(context);
}
public ChildListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public ChildLiistView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
第二种方法计算父Listview的高度,不然子Listview只会显示一个item。此方法不需要重写Listview,直接在适配器中添加如下代码:
/**
* @param listView 此方法是本次listview嵌套listview的核心方法:计算parentlistview item的高度。
* 如果不使用此方法,无论innerlistview有多少个item,则只会显示一个item。
**/
public void setListViewHeightBasedOnChildren(ListView listView) {
// 获取ListView对应的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
// listAdapter.getCount()返回数据项的数目
View listItem = listAdapter.getView(i, null, listView);
// 计算子项View 的宽高
listItem.measure(0, 0);
// 统计所有子项的总高度
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}