private int getListViewHeightBasedOnChildren(Cart1Adapter listAdapter)
{
if (listAdapter == null)
{
return 0;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getGroupCount(); i++)
{
View groupItem = listAdapter.getGroupView(i, false, null, null);
if (null != groupItem)
{
groupItem.measure(0, 0);
totalHeight += groupItem.getMeasuredHeight();
for (int j = 0; j < listAdapter.getChildrenCount(i); j++)
{
View childItem = listAdapter.getChildView(i, j, false,
null, null);
if (null != childItem)
{
// 本身并无意义,但由于android的问题,不在measure之前设置一下宽高可能会导致空指针
RelativeLayout.LayoutParams ll = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
childItem.setLayoutParams(ll);
// childItem.measure(MeasureSpec.makeMeasureSpec(0,
// MeasureSpec.UNSPECIFIED), MeasureSpec
// .makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
childItem.measure(MeasureSpec.makeMeasureSpec(
getResources().getDisplayMetrics().widthPixels,
MeasureSpec.EXACTLY), 0);
totalHeight += childItem.getMeasuredHeight();
}
}
}
}
return totalHeight;
}
我们通常用这个方法来得到整个listview的高度,但是总是有很多空指针问题,在groupItem.measure(0, 0)这一句中,很容易就会报出一个空指针,这是后我们就要看看grouItem中inflate的布局了,如果引入的是LInearlayout是不会有任何问题的,但是如果是RelativeLayout,那么空指针就来了,所以在这个地方出现空指针时请去看看你的布局文件。或者我们可以像下面这样解决问题
RelativeLayout.LayoutParams ll = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
v.setLayoutParams(ll);
这个时候再去取v的高度是不会有问题的。