ScrollView 只能包含一個直接子視圖。若需放入多個佈局/控件,必須將它們包裹在一個根佈局(如 LinearLayout、RelativeLayout、ConstraintLayout)中,再將該根佈局作為 ScrollView 的唯一子視圖。
<ScrollView ...>
<RelativeLayout ... /> <!-- 子視圖1 -->
<LinearLayout ... /> <!-- 子視圖2:編譯報錯或運行崩潰 -->
<TextView ... /> <!-- 子視圖3 -->
</ScrollView>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"> <!-- 內容不足時也撐滿高度 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout ... /> <!-- 原有頂部佈局 -->
<LinearLayout ... /> <!-- 原有中間佈局 -->
<TextView ... /> <!-- 原有底部佈局 -->
<!-- 所有原有佈局依次放入此 LinearLayout -->
</LinearLayout>
</ScrollView>
android:fillViewport="true":當內容高度小於 ScrollView 高度時,強制子視圖撐滿,避免底部空白。layout_height="wrap_content" 讓內容決定高度,從而產生滾動範圍。ConstraintLayout 作為根,需確保約束鏈正確傳遞高度。ConstraintLayout 扁平化。RecyclerView,而非 ScrollView + 大量 View。NestedScrollView 支持嵌套滾動協調(API 21+),配合 CoordinatorLayout/Toolbar 滾動隱藏效果。