今天开发遇到一个问题,就是当动态插入ListView数据的时候,由于之前ListView的高度已经固定死了,所以显示不完整的数据,并且底部显示黑边。如图:


而我希望这个ListView可以动态的改变高度:


当时第一个想到的解决办法就是在setAdapter之后去重新修改ListView的高度,但是发现设置match_parent或wrap_content没有效果,只能设置一个固定的高度。但是显然我的数据长度是不定的,所以设置固定高度不显示。


最后采用的办法是:

[java]view plaincopy

publicvoidsetListViewHeightBasedOnChildren(ListViewlistView){

ListAdapterlistAdapter=listView.getAdapter();

if(listAdapter==null){

return;

}

inttotalHeight=0;

for(inti=0;i<listAdapter.getCount();i++){

ViewlistItem=listAdapter.getView(i,null,listView);

listItem.measure(0,0);

totalHeight+=listItem.getMeasuredHeight();

}

ViewGroup.LayoutParamsparams=listView.getLayoutParams();

params.height=totalHeight

+(listView.getDividerHeight()*(listAdapter.getCount()-1));

((MarginLayoutParams)params).setMargins(10,10,10,10);//可删除

listView.setLayoutParams(params);

}


[html]view plaincopy

<ListView

android:id="@+id/getInfo"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:cacheColorHint="#FFF4F4F4"

android:dividerHeight="0.0dip"

android:fadingEdge="none"//边界黑边

/>