編輯:關於 Android 程式設計
ListView 和 GridView 大家都用得很熟了,摯愛新技術的朋友大概已經全面轉向 RecyclerView。但只要還在用 ListView,你就一定遇過這樣的場景:一個頁面裡除了列表,上方還有輪播圖、篩選欄等內容,直覺做法是整個頁面套一層 ScrollView 一起滑動。結果卻發現——ListView 只顯示了一個 Item,GridView 只顯示一行。
下面我用一個 demo 把現象、原因和幾種解法完整走一遍。
布局中 ScrollView 內嵌套了一個 ListView,注意 ListView 的 layout_height 是 wrap_content:
<LinearLayout android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="https://schemas.android.com/apk/res/android">
<include android:id="@+id/include_header_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/header_home" />
<ScrollView android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView android:layout_width="match_parent"
android:layout_height="380dp"
android:scaleType="fitXY"
android:src="@drawable/center_image" />
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- 商家分類 / 智能排序 / 微送 篩選欄 -->
</LinearLayout>
<ListView android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#33000000"
android:dividerHeight="0.1dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Adapter 明明給了 7 條數據:
class MyAdapter extends BaseAdapter {
@Override public int getCount() { return 7; }
@Override public Object getItem(int position) { return null; }
@Override public long getItemId(int position) { return position; }
@Override public View getView(int position, View convertView, ViewGroup parent) {
return View.inflate(MainActivity.this, R.layout.home_list_item, null);
}
}
運行結果只顯示一項:

ListView 和 GridView 本身就繼承自 ScrollView 家族,都能自己滑動。ScrollView 裡再嵌一個可滑動控件,就會撞上高度測量的問題。
關鍵在於測量模式。ScrollView 對子 View 施加的是 AT_MOST 約束,而系統真正認真測量的只有 EXACTLY 模式(對應 match_parent 和明確數值);AT_MOST 模式下,它只會按內部內容給出一個「合適」的尺寸。而 ListView 的 Item 是通過 getView 一個一個加載出來的——第一個 Item 加載完,它就只測了第一個 Item,於是 ListView 的高度就等於第一個 Item 的高度,剩下的自然顯示不出來。
通過 ViewTreeObserver 在 View 樹繪制完成後取值(在 onCreate 裡直接取會得到 0,因為此時窗體樹還沒繪制完):
mListView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
View firstItemView = mListView.getAdapter().getView(0, null, mListView);
firstItemView.measure(0, 0);
System.out.println("第一個Item的高度:" + firstItemView.getMeasuredHeight());
System.out.println("mListView的高度:" + mListView.getHeight());
}
});
Logcat 輸出:

兩個數值一致,觀點得到驗證。
把布局中的 ListView 改成 android:layout_height="300dp":


這次出現了兩個 Item,但第二項仍顯示不全。原因有兩層:一是 300dp 本身不夠;二是 dp 與 px 的換算——日志與繪制用的都是 px,而 dp 是邏輯單位,用來適配不同分辨率。我的模擬器是 1280×768,換算比為 1:2,所以 300dp 打印出來是 600px;而單個 Item 需要 321px,兩項就是 641px,600 小於 641,當然顯示不全。
這個實驗說明寫死高度能解決顯示問題,但完全不實用:每個 Item 樣式不同、高度不同;數據來自網絡時,條數和總高度都在變。難道每次都去寫死?顯然不行。
不過思路本身是對的——只要改動 ListView 的高度,就能顯示其他 Item。於是問題轉化為:動態測量出合適高度,再動態設置回去。
做法很直接:拿到 Adapter,循環調用每個 Item 的 getView 並 measure,累加高度,最後把總高度設給 ListView(別忘了把分割線算進去)。封裝成工具方法,一行調用即可。
public class MikyouMetricListViewHeightUtils {
public static void setListViewHeight(ListView lv) {
if (lv == null) return;
ListAdapter adapter = lv.getAdapter();
if (adapter == null) return;
int totalHeight = 0;
for (int i = 0; i < adapter.getCount(); i++) {
View listItem = adapter.getView(i, null, lv);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
LayoutParams params = lv.getLayoutParams();
params.height = totalHeight + (lv.getDividerHeight() * (lv.getCount() - 1));
lv.setLayoutParams(params);
}
}
使用時在 setAdapter 之後調用,布局裡的 ListView 保持 wrap_content 即可:
mListView.setAdapter(new MyAdapter());
MikyouMetricListViewHeightUtils.setListViewHeight(mListView);
最終 7 個 Item 全部完整顯示:


驗算一下:單項 321px,7 項共 2247px,6 條分割線各 1px,合計 2253px,與 Logcat 完全一致。
思路與解法一相同,只是把邏輯收進控件內部:
public class MyListView extends ListView {
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(
Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}
這裡用一個極大的 AT_MOST 規格告訴父容器「我盡量大」,讓 ListView 得以完整測量內容。它的優點是調用方零成本,缺點也很明確:一旦 ListView 內部套了 RelativeLayout 等複雜布局,就可能出問題。源碼註釋裡也提到,API 17 及更低版本上 makeMeasureSpec 的參數順序與溢出處理存在缺陷,RelativeLayout 正是受影響的案例。
效果與解法一相同:

說到這裡必須潑一盆冷水:上面這些努力,本質上是在繞過一個不該出現的結構。Google 工程師 Roman Guy 早就明確回覆過——
「There is no need to put a ListView in a ScrollView since ListView already supports scrolling. Do NOT put a ListView inside a ScrollView. ListView already handles scrolling, you're only going to run into trouble.」
更詳細的論述可以看他 在 Google I/O 上關於 ListView 的分享。
既然 ListView 自己就能滑動,那麼把頭部內容也做成它的一個 Item 就行了。做法是把頂部內容抽成獨立布局,主布局只留一個 ListView,然後在 Adapter 中控制 position。
頭部布局 top_listview.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView android:layout_width="match_parent"
android:layout_height="380dp"
android:scaleType="fitXY"
android:src="@drawable/center_image" />
<!-- 篩選欄 -->
</LinearLayout>
主布局:
<LinearLayout android:id="@+id/parent_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="https://schemas.android.com/apk/res/android">
<include android:id="@+id/include_header_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/header_home" />
<ListView android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#33000000"
android:dividerHeight="0.1dp" />
</LinearLayout>
Adapter 的關鍵改動只有兩處:getCount 加一,getView 中判斷 position 為 0 時返回頭部布局並直接 return。
class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return 1 + 7; // 多出的 1 項用來承載頭部內容
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (position == 0) {
// 第一項即頭部內容,加載完直接返回,避免繼續往下執行
return View.inflate(MainActivity.this, R.layout.top_listview, null);
}
return View.inflate(MainActivity.this, R.layout.home_list_item, null);
}
// 其餘方法省略
}
最終效果:

這才是效率最高、也最不容易出後遺症的做法:整頁只有一個可滑動容器,根本不存在嵌套衝突,也順帶解決了滑動嵌套時 ACTION_DOWN 被誰消費的老問題。新項目裡,建議直接採用這種方式。
仿今日頭條與QQ側滑、智慧北京的小專案(三):新聞頁面深度解析
本專案的圖片素材均取自今日頭條;QQ 側滑沒有採用 Android 原生的 NavigationDrawer,而是選用第三方 SlidingMenu,原因是該控制項我暫時
Android 讀取聯絡人姓名與電話號碼的實作程式碼
開發中常有取得聯絡人列表的需求,但這次要做的不是列出整個通訊錄,而是在使用者點選單一聯絡人之後,取出該聯絡人的姓名與電話,並自動填入指定的輸入框,省去手動輸入的麻煩。以下
Android 優雅解決軟鍵盤遮擋按鈕問題
登入頁面若出現軟鍵盤,可能會遮擋登入按鈕。以下提供兩種常見解法。 讓 ScrollView 捲到底部 第一種做法是把表單包在 ScrollView 中。當使用者點擊輸入
Android 自定義 View 打造 QQ 音樂風格旋轉唱片
在音樂播放頁中,旋轉唱片是相當有辨識度的視覺元素。本文說明如何自定義 View,畫出圓形圖片,並透過 Handler 讓它持續旋轉。 測量與繪製圓形圖片 首先要在 onM