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

RelativeLayout 進階:把檢視錨定在父容器的各個角落

編輯:Android 開發教學

使用 RelativeLayout,可以很容易地實現錨定檢視。以下 main.xml 包含五個嵌在 RelativeLayout 中的 Button:

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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Top Right"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Left"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bottom Right"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />

    <Button
        android:id="@+id/button5"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Middle"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

以下屬性分別套用在不同的 Button 上:

layout_alignParentLeft —— 把子檢視置於父檢視內部左側
layout_alignParentRight —— 置於父檢視內部右側
layout_alignParentTop —— 置於父檢視內部頂部
layout_alignParentBottom —— 置於父檢視內部底部
layout_centerVertical —— 置於父檢視垂直中心
layout_centerHorizontal —— 置於父檢視水平中心

這些屬性搭配使用時有個限制值得注意:alignParentTop 與 alignParentBottom 同時設為 true 會讓元件被拉伸填滿整個垂直空間,alignParentLeft 與 alignParentRight 並用則會撐滿水平空間。button5 之所以是 fill_parent 寬度,正是這個道理——它被水平拉伸了。若只想置中而不拉伸,應該改用 layout_centerInParent="true"。

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