当前位置:   article > 正文

Android约束布局的概念与属性(1)

Android约束布局的概念与属性(1)


约束布局(ConstraintLayout)是当前Android Studio默认的布局方式,也是最灵活的一种布局方式。约束布局推荐使用所见即所得的模式进行布局,约束布局的大部分布局可以通过Design视图完成,可以在布局文件的Design视图中采用鼠标拖放操作结合属性栏窗口设置完成约束布局的界面设计,大幅简化布局代码输入和控件间位置关系的人为判断。约束布局的属性非常多,但是不需要强记,可以通过Design页面来认识各种属性。

早期的Android的相对布局(RelativeLayout)基本被约束布局所ConstraintLayout取代,ConstraintLayout使用起来比RelativeLayout更灵活,性能更出色。此外,ConstraintLayout可以按照比例约束控件位置和尺寸,能够更好地适配屏幕大小不同的机型。

约束布局属性主要可以分为:相对定位、边距、居中和偏移、尺寸约束、链等。

1.相对定位约束

相对定位是控件对于另一个控件位置的约束,可以让控件相对于其他控件或父控件进行布局,也可以设置控件相对于其他控件或父控件进行上下左右对齐。如图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" />

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

如图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" />

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

app:layout_constraintBottom_toBottomOf=“@+id/textView9"用于设置该控件与textView9控件底部对齐,app:layout_constraintStart_toStartOf=”@+id/textView10"用于设置该控件与textView10控件的左边对齐。

2.居中和偏移约束

居中可以通过设置距离为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" />

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

上述代码对应的Layout预览图如图4所示。其中app:layout_constraintHorizontal_bias用于设置偏移比例,默认为0.5,即中间位置;图中设置为0.6,即控件位于布局宽度60%的位置。
在这里插入图片描述
图4 居中偏移布局图

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/812790
推荐阅读
相关标签
  

闽ICP备14008679号