Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ListView 塞進 ScrollView 衝突怎麼解?三種方案實測比較

編輯:關於 Android 程式設計

ListView 嵌在 ScrollView 裡,只會顯示一行——這是很多人碰過的坑。以下把網路上常見的三種解法都試過一遍,說明各自的限制。

一、動態計算 ListView 高度

這個流傳最廣的做法有個硬性前提:清單項目的版面必須是 LinearLayout。原因在於其他 Layout(例如 RelativeLayout)並沒有重寫 onMeasure(),直接呼叫 measure 會拋出異常。限制不小。

 public class Utility { public static void setListViewHeightBasedOnChildren(ListView listView) { //獲取ListView對應的Adapter ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { // pre-condition return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; 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); } } 

二、替 ScrollView 加上 fillViewport

有文章說只要加上 android:fillViewport="true" 就能讓 ListView 撐滿整個 ScrollView。實際測試驗證失敗,至少在我的環境裡無效。

三、自訂 ListView / GridView(推薦)

思路是攔下 onMeasure,把高度規格改成 AT_MOST 加大值,強迫控制項量出完整內容高度:

 public class MyListView extends ListView { public MyListView(Context context) { // TODO Auto-generated method stub super(context); } public MyListView(Context context, AttributeSet attrs) { // TODO Auto-generated method stub super(context, attrs); } public MyListView(Context context, AttributeSet attrs, int defStyle) { // TODO Auto-generated method stub super(context, attrs, defStyle); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } } 

GridView 同理:

 /** *自定義gridview,解決ScrollView中嵌套gridview顯示不正常的問題(1行) */ public class MyGridView extends GridView{ public MyGridView(Context context, AttributeSet attrs) { super(context, attrs); } public MyGridView(Context context) { super(context); } public MyGridView(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); } } 

不過要老實說:這種做法等於關掉列表的 view 回收機制,一次把所有項目都配置出來,資料量一大就會明顯卡頓並吃記憶體。真正正確的方向是別把可捲動清單塞進另一個可捲動容器——改用單一 RecyclerView 搭配多種 ItemViewType,或用 CoordinatorLayout 的 collapsing 寫法,才是長久之計。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved