Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

Android 佈局教學:RelativeLayout 相對佈局與常用屬性全整理

編輯:Android 技術基礎

RelativeLayout 是一種相對佈局:控件的位置依「相對關係」決定,後一個控件擺在哪裡,取決於前一個控件的基準位置。它是實際專案中最常用、也最靈活的一種佈局。

一、XML 方式佈局

1. 建立一個空白 Activity。

2. 打開 res/layout/activity_main.xml,根元素維持 RelativeLayout。

① XML 序言,宣告 1.0 版規則與 UTF-8 編碼(也可改為 GB2312);② 根元素為 RelativeLayout;③ 寬高設 match_parent 讓佈局填滿螢幕。

3. 插入三個按鈕,文字分別設為「第一個按鈕」「第二個按鈕」「第三個按鈕」。

接下來的排版目標是:第一個按鈕距左、距上各 20dp;第二個按鈕在第一個下方、與其右邊對齊、上間距 15dp;第三個按鈕在第二個下方、與其左邊對齊、上間距 15dp。

4. 對應的 XML:

① 第一個按鈕:以父容器為基準,貼緊左上,間距 20dp。

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"        // 寬度符合內容
    android:layout_height="wrap_content"       // 高度符合內容
    android:layout_alignParentLeft="true"      // 貼緊父元素左邊
    android:layout_alignParentTop="true"       // 貼緊父元素上邊
    android:layout_marginLeft="20dp"           // 左間距 20dp
    android:layout_marginTop="20dp"            // 上間距 20dp
    android:text="第一個按鈕" />

② 第二個按鈕:以第一個按鈕為基準,在其下方、對齊其右邊。

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button1"        // 位於第一個按鈕下方
    android:layout_toRightOf="@+id/button1"    // 與第一個按鈕右邊對齊
    android:layout_marginTop="15dp"            // 上間距 15dp
    android:text="第二個按鈕" />

③ 第三個按鈕:以第二個按鈕為基準,在其下方、對齊其左邊。

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button2"        // 位於第二個按鈕下方
    android:layout_toLeftOf="@+id/button2"     // 與第二個按鈕左邊對齊
    android:layout_marginTop="15dp"            // 上間距 15dp
    android:text="第三個按鈕" />

最終顯示效果:

相對佈局常用屬性整理

把屬性按「值的型別」分三組,會比死背好記很多。

第一類:值為 true 或 false

  • android:layout_centerHorizontal:水平居中
  • android:layout_centerVertical:垂直居中
  • android:layout_centerInParent:相對於父元素完全居中
  • android:layout_alignParentBottom:貼緊父元素下邊緣
  • android:layout_alignParentLeft:貼緊父元素左邊緣
  • android:layout_alignParentRight:貼緊父元素右邊緣
  • android:layout_alignParentTop:貼緊父元素上邊緣

第二類:值必須是 id 參照,寫成 "@id/id-name"

  • android:layout_below:在某元素下方
  • android:layout_above:在某元素上方
  • android:layout_toLeftOf:在某元素左邊
  • android:layout_toRightOf:在某元素右邊
  • android:layout_alignTop:本元素上邊緣與某元素上邊緣對齊
  • android:layout_alignLeft:本元素左邊緣與某元素左邊緣對齊
  • android:layout_alignBottom:本元素下邊緣與某元素下邊緣對齊
  • android:layout_alignRight:本元素右邊緣與某元素右邊緣對齊

第三類:值為具體尺寸,如 30dp、40px

  • android:layout_marginBottom:距某元素底邊緣的距離
  • android:layout_marginLeft:距某元素左邊緣的距離
  • android:layout_marginRight:距某元素右邊緣的距離
  • android:layout_marginTop:距某元素上邊緣的距離

把這三類屬性自由組合,幾乎能拼出任何你想要的畫面。實務上的一個小提醒:相對佈局雖然靈活,但參照關係寫得太複雜時,效能不一定比一層簡單的 LinearLayout 好,取捨之間要看具體畫面而定。

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