赞
踩
早期的Android的相对布局(RelativeLayout)基本被约束布局所ConstraintLayout取代,ConstraintLayout使用起来比RelativeLayout更灵活,性能更出色。此外,ConstraintLayout可以按照比例约束控件位置和尺寸,能够更好地适配屏幕大小不同的机型。
约束布局属性主要可以分为:相对定位、边距、居中和偏移、尺寸约束、链等。
相对定位是控件对于另一个控件位置的约束,可以让控件相对于其他控件或父控件进行布局,也可以设置控件相对于其他控件或父控件进行上下左右对齐。如图1所示,被选中的TextView控件距离父控件上边缘60dp,距离左边的一个TextView右边缘92dp。
图1 相对定位示例
图1的布局对应的代码如下,其中android:layout_marginStart=“92dp"和app:layout_constraintStart_toEndOf=”@+id/textView6"用于设置该控件的左侧距离textView6控件的右侧92dp。android:layout_marginTop="60dp"和app:layout_constraintTop_toTopOf="parent"用于设置该控件的上侧距离父窗体的上侧60dp。
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="92dp"
app:layout_constraintStart_toEndOf="@+id/textView6"
android:layout_marginTop="60dp"
app:layout_constraintTop_toTopOf="parent"
android:text="TextView" />
如图2所示,被选中的控件分别与上方控件左对齐,与右边的控件底对齐,同样也确定了该控件的位置。一个控件在约束布局中要确定位置,至少要一个垂直方向的约束和一个水平方向的约束。在所有需要对齐的控件被选中的情况下,对齐也可以通过单击Design视图中的工具栏的对齐工具 来完成。
图2 控件对齐示例
图2中被选中控件的布局约束代码如下,
<TextView
android:id="@+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintBottom_toBottomOf="@+id/textView9"
app:layout_constraintStart_toStartOf="@+id/textView10" />
app:layout_constraintBottom_toBottomOf=“@+id/textView9"用于设置该控件与textView9控件底部对齐,app:layout_constraintStart_toStartOf=”@+id/textView10"用于设置该控件与textView10控件的左边对齐。
居中可以通过设置距离为0dp来实现。如果需要将控件水平居中显示,可以将控件水平方向的两个约束设置为0。如果需要将控件垂直居中显示,可以将控件垂直方向的两个约束设置为0。如图3所示,偏移则可以通过Attributes Layout区滑动图中的滑条来实现。
图3 居中偏移控制图
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
上述代码对应的Layout预览图如图4所示。其中app:layout_constraintHorizontal_bias用于设置偏移比例,默认为0.5,即中间位置;图中设置为0.6,即控件位于布局宽度60%的位置。
图4 居中偏移布局图
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。