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

ConstraintLayout 約束布局完全入門

編輯:關於 Android 程式設計

把 Android Studio 升級到 stable 2.2 之後,會發現多了一個 ConstraintLayout。顧名思義,它就是透過各種約束來決定 widget 的呈現方式,最低支援到 API 9。

從 preview 來看滿畫面都是各種線條,感覺相當高級。

使用方式很簡單,先在依賴中加入:

dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha9'
}

寫個最簡單的布局:


這段程式碼的效果,是讓 button 在整個螢幕裡水平居中(垂直方向不居中)。這裡用到了 app:layout_constraintLeft_toLeftOf 和 app:layout_constraintRight_toRightOf 兩個屬性,稍後會詳細解釋。

相對位置屬性

如果要把 button B 放在 button A 的右邊並彼此貼合,可以這樣寫:



layout_constraintLeft_toRightOf 的意思是:buttonB 的左邊緣貼著 buttonA 的右邊緣。注意,這個 toRightOf 和以往 RelativeLayout 的用法不一樣!雖然兩者效果都是把 button B 放到 button A 右邊,但意義不同。除了它之外,還有一系列類似屬性:

layout_constraintLeft_toLeftOf、layout_constraintLeft_toRightOf、layout_constraintRight_toLeftOf、layout_constraintRight_toRightOf、layout_constraintTop_toTopOf、layout_constraintTop_toBottomOf、layout_constraintBottom_toTopOf、layout_constraintBottom_toBottomOf、layout_constraintBaseline_toBaselineOf、layout_constraintStart_toEndOf、layout_constraintStart_toStartOf、layout_constraintEnd_toStartOf、layout_constraintEnd_toEndOf。

可以發現 layout_constraintLeft_toLeftOf 和 layout_constraintRight_toLeftOf 長得很像,只是 toLeftOf 前面的部分不同。若用過去 RelativeLayout 的思路去理解,會以為只是把控件放左邊而已,但其實兩者差很多:

其實這些屬性可以拆成「邊緣 + 對齊方向」來看:

所以 RelativeLayout 的 toRightOf 和 ConstraintLayout 的 Left_toRightOf 並不一樣:RelativeLayout 是把控件當成一個整體,而 ConstraintLayout 是對齊控件四周的邊緣。

理解這點後,再看一個「看似不可能的情況」:


parent 代表父控件,也就是 ConstraintLayout。上面的意思是:按鈕左邊距貼著父控件左邊,右邊距貼著父控件右邊。但父控件填滿整個螢幕,而按鈕又是 wrap_content,沒辦法被拉大,這時系統會讓按鈕在父控件中水平居中(垂直不居中)。

目標控件為 GONE 時的 Margin

過去我們用 android:layout_marginLeft 等屬性控制控件間距。ConstraintLayout 額外提供了「當對齊目標為 gone 時所套用的 margin」。例如:



當 btn1 可見時,效果如下:

當 btn1 設為 gone 時,改用 goneMarginLeft 的間距:

邊距比例

當控件在父控件中水平居中時,如何控制它偏左或偏右的比例?可以透過 layout_constraintHorizontal_bias:

長寬比例

想控制控件的長寬比,可以設定 app:layout_constraintDimensionRatio。過去我們用 layout_width 和 layout_height 決定大小,如果兩者都設成 0dp,效果等同 match_parent。要設定長寬比時,透過 app:layout_constraintDimensionRatio="1:1",格式是「width:height」,但還必須指定長或寬其中一方為固定值:


這種情況下,button 寬度由內容決定,高度則設成與寬度相同。不固定的那一邊一定要設為 0dp——這裡 height 依賴 width,所以設成 0dp。

官網還提到可以寫成 app:layout_constraintDimensionRatio="H,16:9",這部分讀者若有心得也歡迎交流。官方文件:https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html

其他注意事項

要特別留意:ConstraintLayout 中的任何子控件都必須加上約束,否則預設會被繪製在座標 (0, 0) 的位置。

目前 Android Studio 的布局編輯器已經能很好地支援 ConstraintLayout,可以輕鬆地從控件某個邊緣拖曳關聯到另一個控件的邊緣,不必全靠手寫 XML。但要注意:當你用滑鼠隨意拖動控件時,它會停在滑鼠離開的位置,即使完全沒有約束。因此 preview 中呈現的樣子,未必是真正執行後的樣子!

例如下圖,imageView 左邊與上邊關聯 parent,textViewA 左邊貼著 imageView 右邊、上邊與其水平、右邊關聯 parent 右邊;textViewB 左右邊則分別關聯 imageView 的左右邊。

但實際執行起來並非如此。textViewB 其實會顯示在 ImageView 上面並水平居中,因為只指定了水平位置卻沒指定垂直座標,結果如下:

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