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

按鈕欄固定在底部、上方內容可捲動:RelativeLayout 配 ScrollView 的排法

編輯:關於 Android 程式設計

「上方內容可以捲,下方按鈕永遠在」是極常見的版面需求——設定頁、表單頁、詳情頁幾乎都會用到。用 RelativeLayout 就能乾淨地做到,關鍵在於兩個對齊屬性。

版面結構

做法是把 ScrollView 放在自己的內容,另外用 LinearLayout 裝按鈕,兩者都掛在 RelativeLayout 之下。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_alignParentBottom="true"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:orientation="horizontal">

        <Button
            android:text="AAAA"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_weight="1" />

        <Button
            android:text="BBBB"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:layout_weight="1" />
    </LinearLayout>

    <ScrollView
        android:layout_above="@id/buttonLayout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    </ScrollView>

</RelativeLayout>

兩個屬性撐起整個結構

android:layout_alignParentBottom="true" 讓按鈕列無論內容多長,都牢牢貼在父容器的下緣。這是「固定」效果的來源。

android:layout_above="@id/buttonLayout" 讓 ScrollView 的底邊停在按鈕列的上方,而不是佔滿整個父容器。少了這行,ScrollView 會一路延伸到最底部,把按鈕蓋住——這是最常見的失敗寫法。

這裡也說明了為什麼按鈕列必須要有 id:ScrollView 要靠它來定位。

按鈕為什麼要加 layout_weight

兩個 Button 都設 layout_width="fill_parent" 再加上 layout_weight="1",在水平的 LinearLayout 裡就會等分寬度。只寫 fill_parent 而不給 weight,第二顆按鈕會被擠到看不見的地方。

一點延伸

如果按鈕數量不固定,或想讓它們依內容自動換行,把 LinearLayout 替換成其他容器也無妨,只要維持「alignParentBottom 加上 layout_above」這組關係即可。

這次寫完也讓我意識到,幾個常用 Layout 各自的特性還是要好好下一番功夫研究——真正熟練之後,很多需要嵌套三四層才能湊出的效果,其實一個屬性就能解決。

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