listview与scrollview并存时,自动设置listview高度

不说废话,直接上代码,实现功能看标题

//获取adapter
ListAdapter listAdapter = listview.getAdapter();
if (listAdapter == null) {
return;
}

int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listview); //获取子view
//设置子view的大小与父布局无关,这里容易报错后面说
listItem.measure(0, 0);
//累加计算总高度
totalHeight += listItem.getMeasuredHeight();
}

//下面是设置listview的高度
ViewGroup.LayoutParams params = listview.getLayoutParams();
params.height = totalHeight + (listview.getDividerHeight() * (listAdapter.getCount() - 1));
((MarginLayoutParams)params).setMargins(10, 10, 10, 10);
listview.setLayoutParams(params);

listItem.measure(0, 0); 这里容易报NullPointerException异常
是因为在adapter的getView中

convertView = LayoutInflater.from(context).inflate(R.layout.XXX, null);

这里第二个参数如果传null就会出现上面空指针的异常。
改为:

convertView = LayoutInflater.from(context).inflate(
R.layout.XXX, parent, false);

即可,注意第三个参数false必须要传不然会报
java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView

你可能感兴趣的:(android)