ConstraintLayout為一個Support Library,可以用在Android2.3(API 9)以上的版本。
之前在設計畫面的時候都是使用LinearLayout或RelativeLayout,但有時候在比較複雜的畫面,我們疊太多層的Layout會耗比較多的資源,而ConstraintLayout將Layout平面化,減少資源浪費。
增加Library到Project- dependencies {
- compile 'com.android.support.constraint:constraint-layout:1.0.2'
- }
複製代碼 介紹相對定位屬性
Android ConstraintLayout Margin LinearLayout Layout
- <Button
- android:text="Button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/button"
- app:layout_constraintBottom_toBottomOf="parent"
- app:layout_constraintRight_toRightOf="parent"
- app:layout_constraintLeft_toLeftOf="parent"
- app:layout_constraintTop_toTopOf="parent" >
複製代碼
元件在另一個元件的上方
Android ConstraintLayout Margin LinearLayout Layout
- <Button
- android:text="Button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/button2"
- android:layout_marginBottom="48dp"
- app:layout_constraintBottom_toTopOf="@+id/button"
- app:layout_constraintRight_toRightOf="@+id/button"
- app:layout_constraintLeft_toLeftOf="@+id/button">
複製代碼
- layout_constraintBottom_toTopOf : 將button2的下方與button的上方做約束
- layout_constraintRight_toRightOf : 將button2的右邊與button的右邊做約束
- layout_constraintLeft_toLeftOf : 將button2的左邊與button的左邊做約束
所以上面的屬性就都可以依此類推啦~
例如:想要A元件在B元件的左邊就使用
- app:layout_constraintRight_toLeftOf = "@+id/B"
複製代碼- 所有相對定位屬性
- layout_constraintBaseline_toBaselineOf
- layout_constraintTop_toBottomOf
- layout_constraintTop_toTopOf
- layout_constraintBottom_toBottomOf
- layout_constraintBottom_toTopOf
- layout_constraintStart_toEndOf
- layout_constraintStart_toStartOf
- layout_constraintEnd_toEndOf
- layout_constraintEnd_toStartOf
- layout_constraintLeft_toLeftOf
- layout_constraintLeft_toRightOf
- layout_constraintRight_toLeftOf
- layout_constraintRight_toRightOf
MarginMargin的用法和LinearLayout、RelativeLayout的用法相同 - layout_marginStart
- layout_marginEnd
- layout_marginLeft
- layout_marginTop
- layout_marginRight
- layout_marginBottom
而ConstraintLayout還有一些不一樣的Margin - app:layout_goneMarginBottom
- app:layout_goneMarginEnd
- app:layout_goneMarginLeft
- app:layout_goneMarginRight
- app:layout_goneMarginStart
- app:layout_goneMarginTop
goneMargin是在當被依賴的View被設置為Gone的時候所使用的Margin
Android ConstraintLayout Margin LinearLayout Layout
文章出處
|