在ScrollView中使用GridView和ListView

在ScrollView中使用GridView和ListView時,listView和GridView高度是無法控制的
(只有一點點高,並不能使展示全部以滾動條的形式)需要處理:
GridView需要重寫控件的onMeasure
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);


// 在ScrollView中設置listView的寬高
public void setListViewHeightBasedOnChildren(ListView listView) {
// 獲取ListView對應的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
// listAdapter.getCount()返回數據項的數目
View listItem = listAdapter.getView(i, null, listView);
// 計算子項View 的寬高  這個方法只有在LinearLayout纔有效,因爲其他佈局沒有從斜OnMeasure這個方法
listItem.measure(0, 0);
// 統計所有子項的總高度
totalHeight += listItem.getMeasuredHeight();
}


ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
// listView.getDividerHeight()獲取子項間分隔符佔用的高度
// params.height最後得到整個ListView完整顯示需要的高度
listView.setLayoutParams(params);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章