編輯:關於 Android 程式設計
RelativeLayout 是 Android 裡相當靈活的佈局方式,它允許每個子元件相對於父容器、或相對於其他元件來定位。要把這套機制用得好,關鍵就在熟悉它那一大票 layout_ 屬性。本文把它們依用途分類整理,方便隨查隨用。
這類屬性會搭配一個 ID 使用,讓某元件靠著另一個元件擺放:
・android:layout_above:把自己放在指定 ID 元件的上方。
・android:layout_below:把自己放在指定 ID 元件的下方。
・android:layout_toLeftOf:自己的右緣對齊指定元件的左緣。
・android:layout_toRightOf:自己的左緣對齊指定元件的右緣。
・android:layout_alignBaseline:與指定元件的 baseline 對齊。
・android:layout_alignTop:頂緣與指定元件的頂緣對齊。
・android:layout_alignBottom:底緣與指定元件的底緣對齊。
・android:layout_alignLeft:左緣與指定元件的左緣對齊。
・android:layout_alignRight:右緣與指定元件的右緣對齊。
把值設為 true,就能讓元件貼齊父容器的邊:
・android:layout_alignParentTop:頂部對齊父容器頂部。
・android:layout_alignParentBottom:底部對齊父容器底部。
・android:layout_alignParentLeft:左部對齊父容器左側。
・android:layout_alignParentRight:右部對齊父容器右側。
・android:layout_centerHorizontal:水平置中。
・android:layout_centerVertical:垂直置中。
・android:layout_centerInParent:置於父容器正中央。
margin 是元件「外部」留白,padding 則是元件「內部」內容與邊框之間的留白,兩者都支援四個方向:
・外边距:android:layout_marginLeft / Top / Right / Bottom。
・内边距:android:paddingLeft / Top / Right / Bottom,以及四邊一起設的 android:padding。
例如 android:paddingLeft="15sp" 代表內容距離左邊框 15sp;android:layout_marginLeft="5px" 則代表這個元件與它左邊的元件間隔 5px。
以下幾個雖然不限於 RelativeLayout,但搭配起來非常實用:
・android:id:為元件指定 ID。
・android:text:顯示的文字,建議用 strings.xml 管理。
・android:textSize:字級大小。
・android:background:背景色,可用 #FFFFFF 或 @android:color/white。
・android:singleLine:設為 true 時,內容只顯示在同一行。
・android:gravity:控制元件「內容」在元件內的位置(置中、靠右等)。
・android:layout_gravity:控制元件「本身」相對於父容器的位置。
這是在 LinearLayout 裡常見、但觀念上容易混淆的屬性。每個子 View 都有 layout_weight,預設為 0,代表「需要多大就佔多大」。一旦給了正值,父容器會依各子元件的權重比例來瓜分剩餘空間。舉例來說,兩個輸入框若權重都設為 1,就平分剩餘寬度;若設成 1 與 2,則第一個分到三分之二、第二個分到三分之一——數值越小,重要性反而越高。
android:layout_below="@+id/title" android:layout_alignBaseline="@+id/subtitle" android:layout_alignParentTop="true" android:layout_marginLeft="10px"
把這些屬性記熟,RelativeLayout 就能排出各種緊湊又精準的介面;真正常見的困擾,往往只是忘了 margin 與 padding 的界線在哪裡而已。
ANDROID L —— Material Design 詳解(UI 控件)
Android L:Google 已確認 Android L 即 Android Lollipop(5.0)。近來 Android 5.0 正式版 SDK 已可下載,首批
玩轉 Android Studio:常用快捷鍵與調試技巧
Android Studio 作為現在 Android 開發的主流 IDE,提供了大量提升效率的功能。掌握一些常用快捷鍵和調試技巧,可以讓日常開發更加順手。本文將從日志、
LinearLayout 實戰:權重配置與資源檔的組織方式
LinearLayout 是最基礎的版面容器,把所有子元件排成一條直線。要把它用好,關鍵在 orientation 與 layout_weight 這兩個屬性,以及資源檔
Android 插件化探索(三):免安裝執行 Activity 的兩種思路(上)
前情提要:資源載入的差異 在討論免安裝執行 Activity 之前,先釐清兩個容易混淆的資源取得方式。getResourcesForApplication 需要傳入套件名