Android ListView高度自適應和ScrollView沖突解決


在ScrollView中嵌套使用ListView,ListView只會顯示一行到兩行的數據。起初我以為是樣式的問題,一直在對XML文件的樣式進行嘗試性設置,但始終得不到想要的效果。后來在網上查了查,ScrollView和ListView兩個View都有滾動的效果,在嵌套使用時起了沖突,一般不建議兩者套用。

 

下面說說具體解決方案。方案的主要思路就是根據ListView子項重置其高度。

首先,ListView不能直接用,要自定義一個,然后重寫onMeasure()方法:

 1 import android.content.Context;
 2 import android.util.AttributeSet;
 3 import android.widget.ListView;
 4 
 5 public class MyListView extends ListView {
 6 
 7     public MyListView(Context context) {
 8     super(context);
 9     }
10     
11     public MyListView(Context context, AttributeSet attrs) {
12     super(context, attrs);
13     }
14     
15     public MyListView(Context context, AttributeSet attrs, int defStyle) {
16     super(context, attrs, defStyle);
17     }
18     
19     @Override
20     public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
21         int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
22                 MeasureSpec.AT_MOST);
23         super.onMeasure(widthMeasureSpec, expandSpec);
24     }
25 
26 }

第二步:寫個計算listView每個Item的方法:

 1 public void setListViewHeightBasedOnChildren(ListView listView) {
 2 
 3   // 獲取ListView對應的Adapter
 4 
 5   ListAdapter listAdapter = listView.getAdapter();
 6 
 7   if (listAdapter == null) {
 8 
 9    return;
10 
11   }
12 
13   int totalHeight = 0;
14 
15   for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回數據項的數目
16 
17    View listItem = listAdapter.getView(i, null, listView);
18 
19    listItem.measure(0, 0); // 計算子項View 的寬高
20 
21    totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度
22 
23   }
24 
25   ViewGroup.LayoutParams params = listView.getLayoutParams();
26 
27   params.height = totalHeight
28     + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
29 
30   // listView.getDividerHeight()獲取子項間分隔符占用的高度
31 
32   // params.height最后得到整個ListView完整顯示需要的高度
33 
34   listView.setLayoutParams(params);
35 
36  }

在設置LIstView的Adapter后調用此方法便可。

 

但是要注意的是,子ListView的每個Item必須是LinearLayout,不能是其他的,因為其他的Layout(如RelativeLayout)沒有重寫onMeasure(),所以會在onMeasure()時拋出異常。

 

1 listView.setAdapter(adapter);  
2 setListViewHeightBasedOnChildren(listView);  

 

謝謝作者:http://www.jb51.net/article/37202.htm,http://blog.csdn.net/wulianghuan/article/details/8627958

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM