需求很簡單卻有點惱人:五個 TextView 要平均、等距地從上到下鋪滿整個畫面。直接把五個 view 用 layout_below 串起來,間距會完全由內容高度決定,看起來就是上密下疏。把這個做法寫成筆記,以後直接複用。
外層是一個相對佈局,先釘住三個錨點:第一個貼齊頂端(layout_alignParentTop)、第三個置中(layout_centerInParent)、第五個貼齊底部(layout_alignParentBottom)。
接著處理第二個。若直接寫成「在第一個下方、第三個上方」,你會發現它離第一個很近、離第三個很遠——因為上下約束只規定了區間,沒有規定了它在區間中的位置。解法是在第二個外層再包一個 RelativeLayout,寬高都設 fill_parent,並用 layout_below / layout_above 把它夾在第一與第三之間,然後讓第二個在這個容器裡 layout_centerInParent。第四個如法炮製。
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/mMainFirst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:padding="@dimen/padding_medium"
android:background="@drawable/ic_launcher"
android:text="第一行"
tools:context=".MainActivity" />
<TextView
android:id="@+id/mMainThird"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="@dimen/padding_medium"
android:background="@drawable/ic_launcher"
android:text="第三行"
tools:context=".MainActivity" />
<TextView
android:id="@+id/mMainFifth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:padding="@dimen/padding_medium"
android:background="@drawable/ic_launcher"
android:text="第五行"
tools:context=".MainActivity" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/mMainFirst"
android:layout_above="@id/mMainThird">
<TextView
android:id="@+id/mMainSecond"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="@dimen/padding_medium"
android:background="@drawable/ic_launcher"
android:text="第二行"
tools:context=".MainActivity" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/mMainThird"
android:layout_above="@id/mMainFifth">
<TextView
android:id="@+id/mMainFourth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="@dimen/padding_medium"
android:background="@drawable/ic_launcher"
android:text="第四行"
tools:context=".MainActivity" />
</RelativeLayout>
</RelativeLayout>
如果你在 API 較新的專案裡實作同樣效果,LinearLayout 加上 android:layout_weight 會更省事;但這套「錨點 + 中央容器」的寫法在需要交錯排列或搭配其他約束時,仍然很好用。