常見需求:頁面內容可滾動,底部按鈕固定不動。本文通過實戰案例,詳細講解 ScrollView 在 RelativeLayout 中的正確放置姿勢,解決「只能有一個直接子 View」與「底部固定」的雙重約束。
原始代碼將 ScrollView 直接放在 RelativeLayout 根節點,並未限制高度,導致 ScrollView 佔滿全屏,底部按鈕被覆蓋或推出可視區。關鍵問題:
ScrollView 未設置 layout_above="@id/button"。ScrollView 高度設為 fill_parent 而非 wrap_content。ScrollView 只接受一個直接子 View)。<RelativeLayout xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- 底部固定按鈕 -->
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Exit" />
<!-- 內容滾動區:高度佔滿按鈕上方空間 -->
<ScrollView
android:id="@+id/scrollview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/button1"
android:layout_alignParentTop="true">
<!-- 唯一直接子 View:垂直 LinearLayout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- 三列佈局容器 -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!-- 第 1 列 -->
<LinearLayout ... android:layout_weight="1">...</LinearLayout>
<!-- 第 2 列 -->
<LinearLayout ... android:layout_weight="1">...</LinearLayout>
<!-- 第 3 列 -->
<LinearLayout ... android:layout_weight="1">...</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</RelativeLayout>
| 屬性 | 作用 |
|---|---|
android:layout_above="@id/button1" | 限制 ScrollView 底部不超過按鈕頂部 |
android:layout_height="wrap_content" | ScrollView 高度自適應內容,配合 above 實現「佔滿剩餘空間」 |
android:layout_alignParentTop="true" | 頂部對齊父容器 |
內層 LinearLayout orientation="vertical" | 滾動方向為垂直 |
android:layout_height="match_parent" + android:fillViewport="true"(在 ScrollView 上)。ConstraintLayout + NestedScrollView(Support Library),性能更優。掌握「固定邊界 + 滾動區域」佈局模式,輕松應對各類固定底部/頂部導航需求。