今天开发遇到一个问题,就是当动态插入ListView数据的时候,由于之前ListView的高度已经固定死了,所以显示不完整的数据,并且底部显示黑边。
解决方法一如下:
首先考虑到如果要实现界面的滚动,需要使用ScrollView控件,该方法就是使用ScrollView控件实现ListView高度的动态设置。
activity中添加下面函数
<span style="font-family:Microsoft YaHei;font-size:18px;">public void setListViewHeightBasedOnChildren(ListView listView) {
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);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
((MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 可删除
listView.setLayoutParams(params);
}
</span>
xml 文件代码如下:
<span style="font-family:Microsoft YaHei;font-size:18px;"><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" // 边界黑边
/> </span>
ScrollView中放置ListView动态设置ListView高度的时候需要如下面的布局:
<span style="font-family:Microsoft YaHei;font-size:18px;"><ScrollView
android:id="@+id/feedbacklayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingLeft="0px">
<ListView
android:id="@+id/mySalesPromotionListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="5.0dip"
android:layout_marginRight="5.0dip"
android:textColor="#000"
android:textSize="16.0dip" >
</ListView>
</LinearLayout>
</ScrollView></span>
解决方法二如下:
使用ListView控件的特有属性:android:scrollbars="vertical",该属性有三个值。none(隐藏),horizontal(水平),vertical(垂直)。