編輯:關於 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 在尚未被明確給定高度時,只會配置到剛好顯示一項的空間。
在 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);
這個方法是在多次嘗試失敗後自己想出來的。

版面配置裡只放一個 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);
既然 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);
與解法 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);
這個是我在寫 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。
Android 打造旋轉木馬風格的音樂播放效果
一、靈感來源:百度在線音樂的旋轉木馬效果 就是畫面上這個效果——當音樂播放時,那張光碟輪子會像旋轉木馬一般不停轉動,看起來相當有趣。剛好想起前陣子做過音樂播放器,於是一
Android 讀取 assets 中的 Excel 並顯示於列表
本文分享如何讀取 assets 目錄下的 Excel 檔案並呈現在畫面上,供需要的朋友參考。 一、前置準備 1、在 assets 目錄放入 Excel 檔,命名為 exc
Android for Work 實戰總結(下):流程演示與 EMM 配置
Afw 流程演示Device Owner(L 平台)先把設備恢復出廠設置,接著連接可翻牆的 Wi-Fi,直到出現如下引導界面:點擊「Set up work device」
Android 源碼解析(十四):Activity 啟動流程
Activity 是 Android 應用中最核心的組件之一。理解 Activity 的啟動流程,不僅能幫助我們更好地掌握 Android 系統的工作機制,也能讓我們在面