在ScrollView中嵌套使用ListView,ListView只會顯示一行到兩行的數據。起初我以為是樣式的問題,一直在對XML文件的樣式進行嘗試性設置,但始終得不到想要的效果。后來在網上查了查,ScrollView和ListView兩個View都有滾動的效果,在嵌套使用時起了沖突,一般不建議兩者套用。
下面說說具體解決方案。方案的主要思路就是根據ListView子項重置其高度。
首先,ListView不能直接用,要自定義一個,然后重寫onMeasure()方法:
import android.content.Context; import android.util.AttributeSet; import android.widget.ListView; public class MyListView extends ListView { public MyListView(Context context) { super(context); } public MyListView(Context context, AttributeSet attrs) { super(context, attrs); } public MyListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
第二步:寫個計算listView每個Item的方法:
public void setListViewHeightBasedOnChildren(ListView listView) { // 獲取ListView對應的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回數據項的數目 View listItem = listAdapter.getView(i, null, listView); listItem.measure(0, 0); // 計算子項View 的寬高 totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度 } ViewGroup.LayoutParams params = listView.getLayoutParams(); params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); // listView.getDividerHeight()獲取子項間分隔符占用的高度 // params.height最后得到整個ListView完整顯示需要的高度 listView.setLayoutParams(params); }
在設置LIstView的Adapter后調用此方法便可。
但是要注意的是,子ListView的每個Item必須是LinearLayout,不能是其他的,因為其他的Layout(如RelativeLayout)沒有重寫onMeasure(),所以會在onMeasure()時拋出異常。
1 listView.setAdapter(adapter); 2 setListViewHeightBasedOnChildren(listView);
