在工作中,我們會遇到需要在ScollView中嵌套ListView的問題,但如果在ScollView中嵌套普通的ListView會出現隻顯示一行的問題.
是以我的解決辦法有三種:
一,在代碼中寫個計算每個item的高度解決:
public void setListViewHeightBasedOnChildren(ListView listView) {
// 擷取ListView對應的Adapter
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = ;
for (int i = ; i < listAdapter.getCount(); i++) { // listAdapter.getCount()傳回資料項的數目
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(, ); // 計算子項View 的寬高
totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - ));
// listView.getDividerHeight()擷取子項間分隔符占用的高度
// params.height最後得到整個ListView完整顯示需要的高度
listView.setLayoutParams(params);
}
二,寫一個自定義ListView,重寫onMesure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> ,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
三,listview添加擴充卡後,設定高度:
listView.setAdapter(adapter);
new ListViewUtil().setListViewHeightBasedOnChildren(listView)
但第一種方案有問題,在低版本的android手機上回沒有效果,具體哪個版本我也不太清楚,但4.2版本的手機會出現沒有效果的這種情況,是以我建議使用第二種方案.