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

ScrollView 嵌套 ListView 的五種解法與優缺點全面比較

編輯:關於 Android 程式設計

實務上很常遇到 ScrollView 裡塞 ListView 的需求,網路上的解法五花八門卻往往講不清楚。我陸續試過多種做法,各有取捨,以下從「為什麼要這樣做」、「會出什麼問題」、「有哪些解法」、「各自優缺點」四個角度完整梳理。以下以 ListView 代稱,結論同樣適用於繼承 AbsListView 的 ExpandableListView、GridView 等。

一、為什麼會出現這種結構

ScrollView 與 ListView 都是可捲動控件,功能看似重疊。但實際產品設計常常長這樣:

例如天貓商城「確認訂單」頁面,ScrollView 中嵌套了 ExpandableListView,上方與下方各有固定內容,整體又要能一起捲動。列表資料夾在固定資料中間並隨整體滾動,於是就出現了這個看似奇怪的組合。

二、會碰到的問題

先看一段直覺但會失敗的寫法:

<ScrollView
    android:id="@+id/act_solution_1_sv"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="\nListView上方數據\n" />

        <ListView
            android:id="@+id/act_solution_1_lv"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="\nListView下方數據\n" />
    </LinearLayout>
</ScrollView>

ScrollView 只能放一個直接子節點,通常放 orientation 為 vertical 的 LinearLayout,ListView 高度設為 wrap_content。看起來沒問題,實測卻是:

黑框處是 ListView,明明塞了 20 筆資料,卻只顯示 1 筆。屬性設定無誤,為什麼不按預期走?

原因在於捲動事件的消費處理,以及 ListView 自身高度的量測方式:ListView 在尚未被明確給定高度時,只會配置到剛好顯示一項的空間。

三、五種解法

解法 1:手動計算並設定 ListView 高度

在 XML 中直接寫死高度確實可行,但列表項目數量是可變的,所以必須在程式碼中實測。

/**
 * 動態設置 ListView 的高度
 */
public static void setListViewHeightBasedOnChildren(ListView listView) {
    if (listView == null) return;

    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter == null) {
        // pre-condition
        return;
    }

    int totalHeight = 0;
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(0, 0);
        totalHeight += listItem.getMeasuredHeight();
    }

    ViewGroup.LayoutParams params = listView.getLayoutParams();
    params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
    listView.setLayoutParams(params);
}

在設定 Adapter 之後呼叫即可。兩個細節要注意:一是 getView 回傳的 View 頂層佈局必須是 LinearLayout,因为只有它才有可用的 measure() 實作,若使用 RelativeLayout 會直接拋例外;二是使用此法後 ScrollView 預設會停在 ListView 的位置,需要手動滾回頂端:

sv = (ScrollView) findViewById(R.id.act_solution_1_sv);

解法 2:只用一個 ListView 承載全部內容

這個方法是在多次嘗試失敗後自己想出來的。

版面配置裡只放一個 ListView:

<ListView
    android:id="@+id/act_solution_2_lv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</ListView>

原本 ListView 上方與下方的資料,各自獨立成兩個 XML 檔。

Java 端自定義 Adapter,在 getView 中依 position 決定要 inflate 哪個佈局:

public View getView(int position, View convertView, ViewGroup parent) {
    // 列表第一項
    if (position == 0) {
        convertView = inflater.inflate(R.layout.item_solution2_top, null);
        return convertView;
    }
    // 列表最後一項
    else if (position == 21) {
        convertView = inflater.inflate(R.layout.item_solution2_bottom, null);
        return convertView;
    }

    // 普通列表項
    ViewHolder h = null;
    if (convertView == null || convertView.getTag() == null) {
        convertView = inflater.inflate(R.layout.item_listview_data, null);
        h = new ViewHolder();
        h.tv = (TextView) convertView.findViewById(R.id.item_listview_data_tv);
        convertView.setTag(h);
    } else {
        h = (ViewHolder) convertView.getTag();
    }

    h.tv.setText("第" + position + "條數據");
    return convertView;
}

Activity 端只需掛上這個 Adapter:

lv = (ListView) findViewById(R.id.act_solution_2_lv);
adapter = new AdapterForListView2(this);
lv.setAdapter(adapter);

解法 3:用 LinearLayout 取代 ListView

既然 ListView 不適應 ScrollView,換一個能適應的控件就好。若想繼續沿用已寫好的 Adapter,可以自定義一個繼承 LinearLayout 並對 BaseAdapter 做適配的類別:

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;

/**
 * 取代 ListView 的 LinearLayout,使之能夠成功嵌套在 ScrollView 中
 */
public class LinearLayoutForListView extends LinearLayout {

    private BaseAdapter adapter;
    private OnClickListener onClickListener = null;

    /**
     * 綁定布局
     */
    public void bindLinearLayout() {
        int count = adapter.getCount();
        this.removeAllViews();
        for (int i = 0; i < count; i++) {
            View v = adapter.getView(i, null, null);
            v.setOnClickListener(this.onClickListener);
            addView(v, i);
        }
        Log.v("countTAG", "" + count);
    }

    public LinearLayoutForListView(Context context) {
        super(context);
    }
    // 其餘構造方法略
}

把 XML 中的 ListView 換成這個類別:

<com.example.mywidgets.LinearLayoutForListView
    android:id="@+id/act_solution_3_mylinearlayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
</com.example.mywidgets.LinearLayoutForListView>

Activity 中同步替換型別:

mylinearlayout = (LinearLayoutForListView) findViewById(R.id.act_solution_3_mylinearlayout);
adapter = new AdapterForListView(this);
mylinearlayout.setAdapter(adapter);

解法 4:自定義可適應 ScrollView 的 ListView

與解法 3 異曲同工,但如果你堅持要用 ListView,就繼承它並覆寫 onMeasure():

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

public class ListViewForScrollView extends ListView {

    public ListViewForScrollView(Context context) {
        super(context);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ListViewForScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 覆寫該方法,達到使 ListView 適應 ScrollView 的效果
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}

三個構造方法完全不用動,改動量遠小於解法 3。XML 與 Activity 中把 ListView 換成這個自定義型別即可。它與解法 1 有一樣的小毛病:預設會停在 ListView 處,需要手動滾回頂端:

sv = (ScrollView) findViewById(R.id.act_solution_4_sv);
sv.smoothScrollTo(0, 0);

解法 5:設定 fillViewport(無法達到預期效果)

這個是我在寫 Demo 時無意發現的,原本以為一行屬性就能解決:

<ScrollView
    android:id="@+id/act_solution_5_sv"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_below="@+id/act_solution_5_vg_top"
    android:fillViewport="true">

結果 ListView 確實填滿了 ScrollView 的剩餘空間,卻完全不能捲動——這是致命缺陷,因此只能列為無效方案。

四、優缺點比較

解法 1:優點是不必改動任何控件,拿一個現成方法即可。最大限制是 item 佈局必須完全由 LinearLayout 組成,複雜佈局不適用。若你的列表項簡單、又急著解決問題,這個方法最省事。

解法 2:優點是佈局設計單純、Activity 程式碼少。缺點是自定義 Adapter 變複雜,且效率會下降——findViewById 本身就耗時,而 headerview/footerview 混在列表中也會破壞 ViewHolder 複用結構。適合列表項少、上下固定資料少、互動少的簡單場景。

解法 3:優點是徹底解決嵌套問題且程式碼不多,甚至可以直接用 LinearLayout 手動 addView(記得先呼叫 removeAllViews(),否則容易出現意料之外的行為)。缺點有兩個:不是系統控件,無法在 Graphical Layout 預覽中直接看到效果;也不能用 ViewHolder 結構,子項多時會耗時在 findViewById。資料量不大時相當好用。

解法 4:比解法 3 更簡單、程式碼更少,同時保留 ListView 原有能力(包含 notifyDataSetChanged()),是最接近完美的方案,只需在 Activity 中把 ScrollView 滾回頂端。如果還在猶豫,選它就對了。

實務上的建議:資料量小且互動單純時優先考慮解法 4;列表項結構簡單又趕時間時用解法 1;需要大量項目與複用機制時,其實更該重新思考設計,例如改用 RecyclerView 搭配多種 item type,而不是硬把 ListView 塞進 ScrollView。

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