最開始接觸ConstraintLayout,完全依賴于拖曳方式實現(xiàn)布局,而在實際操作過程中,完全通過拖曳其實效率反倒是會打折扣,覺得還是有必要結(jié)合xml編碼來實現(xiàn)布局。總結(jié)一些常用的ConstraintLayout的XML屬性如下:
1.相對定位
layout_constraint(1)_to(2)Of="(3)"
(1):控件自身對應的位置
(2):相對于約束控件的位置
(3):指定約束的控件:可以為具體的控件id 或者parent
如下:
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 // 文本內(nèi)容基準線對齊
layout_constraintStart_toEndOf // 起始邊向尾部對齊
layout_constraintStart_toStartOf // 起始邊向起始邊對齊
layout_constraintEnd_toStartOf // 尾部向起始邊對齊
layout_constraintEnd_toEndOf // 尾部向尾部對齊
2.GONE MARGIN
對應位置的控制可見時通過傳統(tǒng)的layout_margin設置,layout_goneMargin當不可見的時候的邊距值。如下:
layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom
3.傾斜比例
當控件這樣設置的時候為居中
layout_constraintLeft_toLeftOf="parent"
layout_constraintRight_toRightOf="parent
在此基礎上可增加傾斜的比例
水平: layout_constraintHorizontal_bias
垂直: layout_constraintVertical_bias
例如:左邊占40%,右邊占60%
layout_constraintHorizontal_bias="0.4"
4.最小寬高
當寬或高設置屬性為WRAP_CONTENT時可以設置最小寬高
android:minWidth 設置布局的最小寬度
android:minHeight 設置布局的最小高度
5.寬高比:layout_constraintDimensionRatio
設置控件的寬高比例時,控件的寬或者高必須有一個設置為0dp或者MATCH_CONSTRAINT。重點是以水為基準來確定寬高比
第一種情況:
寬或高1個為0dp或MATCH_CONSTRAINT,另一個為具體值或者wrap_content時。
已具體值的寬或高為標準,另一方按照其比例設置大小

android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintDimensionRatio="4:1"
如上高大小確定,寬是高的4倍
第二種情況:
寬和高都為0dp或MATCH_CONSTRAINT,已確定邊為基準,另一邊按比例設置大小

上圖button_1:layout_constraintDimensionRatio="2:1"
高確定,所以寬是高的2倍
上圖button_2:layout_constraintDimensionRatio="3:1"
寬確定,所以高是寬的三分之一
還有另外一種寫法不過不推薦:layout_constraintDimensionRatio="H,16:9"這了制定了W,H。
這里的W或H和后面的比例有點難理解。實踐了下大概是這個意思:假設比例設置為a:b ,如果前面是H,不論哪一邊確定,另外一邊的大小都是確定邊的b/a倍;如果前面是W,不論哪一邊確定,另外一邊的大小都是確定邊的a/b倍。