編輯:關於 Android 程式設計
相比線性佈局與表格佈局,RelativeLayout 的彈性明顯更高,實務上出現的頻率也最高。它的核心概念只有一句話:每個控制項的位置,是相對於父容器或兄弟控制項決定的。只要先定錨一個元件,其他元件就能靠著它一路排下去。
這次要做出的畫面如下:

結構很簡單:一個 TextView 當標題、一個 EditText 讓使用者輸入、兩個 Button 並排靠右。
相對於其他控制項:
android:layout_above:把自己的底邊貼到指定 id 的下方元件之上。
android:layout_below:把自己的頂邊放到指定 id 的下方。
android:layout_toLeftOf:把自己的右邊緊貼在指定 id 的左側。
android:layout_toRightOf:把自己的左邊緊貼在指定 id 的右側。
相對於父容器對齊:
android:layout_alignParentRight:右邊與父容器右緣對齊。
android:layout_alignParentLeft:左邊與父容器左緣對齊。
android:layout_alignParentTop:頂端與父容器頂緣對齊。
android:layout_alignParentBottom:底端與父容器底緣對齊。
與指定控制項的邊緣對齊:
android:layout_alignBottom、android:layout_alignLeft、android:layout_alignRight、android:layout_alignTop,分別對應底部、左邊、右邊、頂端的對齊。
整個畫面只靠相對定位就能完成,不需要任何巢狀容器:
<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"
android:padding="10px">
<TextView
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/input_dis"
tools:context=".MainActivity" />
<EditText
android:id="@+id/edit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/input"
android:background="@android:drawable/editbox_background" />
<Button
android:id="@+id/ok"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="@id/edit"
android:layout_alignParentRight="true"
android:layout_marginLeft="10px"
android:text="@string/ok" />
<Button
android:id="@+id/cancel"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="@id/edit"
android:layout_toLeftOf="@id/ok"
android:text="@string/cancel" />
</RelativeLayout>
這裡有兩個值得留意的技巧。第一,EditText 用 layout_below="@id/input 接在標題下方,形成由上而下的骨架。第二,兩個按鈕都掛在 EditText 下方,但「確定」按鈕靠父容器右緣對齊,「取消」按鈕則用 layout_toLeftOf="@id/ok" 貼在確定鈕的左邊——先放好錨點,再讓其他元件靠過來,這就是相對佈局的思考順序。
另外提醒一個實務上的地雷:在 RelativeLayout 裡,被當成參照的元件必須先在 XML 中出現,否則 id 找不到,會直接導致編譯或執行期錯誤。
RelativeLayout ROP 屬性雖多,但本質只有「上下左右」與「對齊誰」兩類。用得夠熟之後,很多原本需要三四層 LinearLayout 才能拼出的畫面,用一層 RelativeLayout 就能搞定,效能與可讀性都更好。
作者:tornadomeet
Android Activity(活動)全面詳解
Activity 是 Android 四大元件之一,幾乎每一個可見的應用介面背後都有一個 Activity 在支撐。本文將從專案結構、日誌工具一路談到 Activity
Android 6.0 源碼下載、編譯與 Nexus 6P 刷機完整實錄
前言 本文記錄從下載 Android 6.0.1 AOSP 源碼、編譯、處理驅動,到刷入 Nexus 6P 的完整過程。這個過程涉及環境準備、repo 同步、編譯、解鎖、
自定義 View 實作教學:帶小圓點的倒數計時圓形進度條
上一篇我們做了一個可以隨時暫停的圓形進度條,這次換個花樣,來做一個「外圈是倒數計時、弧線末端還跟著一顆小圓點」的 View。整個元件裡最麻煩的地方,就在於那顆小圓必須隨著
仿開心消消樂:大樹星星無限循環滾動與點擊效果(自訂 View 實作)
先上效果圖這是我專案中的實際效果:下面是我抽取出來的 demo,各項適配基本都已處理好:下面來說說思路。先講原理:我用 Bitmap 建立兩張圖,一開始一張在下方(記為