原文:
http://www.lxweimin.com/p/16e95b6b5e38
http://www.lxweimin.com/p/575829baa39d
如何閱讀 xml 屬性
與 Relativelayout 不同,ConstrainLayout 的屬性需要同時說明需要怎么操作自己與目標控件,例如:layout_constraintLeft_toLeftOf 指自身左邊緣與目標控件左邊緣對齊
從此 match_parent 是故人
ConstraintLayout 里不再使用 match_parent,想要鋪滿屏幕,只能設置寬度為 0,并添加左右邊緣與父容器的約束。(想要實現 match_parent的效果,切記要設置該方向大小為 0dp)
android:layout_width="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
穿了馬甲的 LinearLayout
線性布局的 weight 屬性可以輕松實現等分操作。在 ConstraintLayout 里你也可以實現類似的功能:
app:layout_constraintHorizontal_bias=".3" //數值范圍:0~1
如果控件已約束了左右邊緣且定義了 bias 為 0.3,則意味著控件與左邊緣的距離占控件左右邊緣間距的 30%,如圖:
bias
甚至想要實現 LinearLayout 的 weight=1 等分操作(例如水平方向上等分)也很簡單,每個相鄰控件互為約束并設置 width=0dp 即可。這樣其實就組成了鏈(chaining)。
鏈
像上面說到的,設置 width=0,且控件之間兩兩互相約束,即可實現水平方向等分。此時還可以給控件設置 layout_constraintHorizontal_weight 屬性,該屬性與 LinearLayout 中的 weight 類似。
鏈條頭部的屬性
水平鏈的最左邊,垂直鏈的最上邊稱之為頭部,鏈的頭部可以設置鏈的屬性:
app:layout_constraintHorizontal_chainStyle="spread"
app:layout_constraintVertical_chainStyle="packed"
spread 默認屬性,平均分布
spread_inside 首尾無間距
packed 控件間無間距,可以同時搭配 layout_constraintHorizontal_bias 屬性控制與父容器的間距
各屬性值的樣式如下:
各屬性樣式
厲害了,還能設寬高比
app:layout_constraintDimensionRatio="1:1" //寬:高
該屬性起作用的前提是寬或高至少有一個設為 0dp,設為 0dp 的邊即為隨比例縮放的邊。
舉個栗子:
android:layout_width="wrap_content"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="1:1"/>
該文本框在隨著內容文字的增加,寬度會越來越大,一旦設定了寬高比為1,則在寬度增大時高度也會等比增大,一直保持在寬高比1:1。
寬高比還有另外的妙用,比如一個控件左右邊緣已存在與父容器約束,且同時將寬高都設為 0dp,便得到水平方向上鋪滿屏幕的效果,如圖:
寬高均設為0
指示線 Guideline
指示線不會被繪制到 UI 中,所以放心大膽地用。Guideline 的一些屬性:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline"
app:layout_constraintGuide_percent="0.5" //設置位置比例
android:orientation="vertical"/> //不注明該屬性,則默認是水平方向
app:layout_constraintGuide_begin="30dp" //設置與頭部邊距
app:layout_constraintGuide_end="30dp" // 設置與尾部邊距
其他
layout_goneMarginLeft 屬性,當有約束關系的控件被置為 gone 狀態時,可以通過設置該屬性來控制間距
動畫
[譯]Constraint Layout 動畫 |動態 Constraint |用 Java 實現的 UI(這到底是什么)[第三部分]
作者:揚州慢_
鏈接:http://www.lxweimin.com/p/16e95b6b5e38
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。