今天開發遇到一個問題,就是當動態插入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(垂直)。