ConstraintLayout简单使用

作者: yangchendev | 来源:发表于2018-04-12 15:50 被阅读0次

    前言

    目前最新的Android Studio 新建Activity后默认使用ConstraintLayout,相比相对布局和线性布局,它在位置定位和控件大小的操作方面更加方便,而且视图树更加趋于扁平,能有效减少在测量、摆放和绘制上时间和性能方面的消耗。
    约束布局的相对位置类似于相对布局,但是它的功能更加强大。

    相对位置

    一个控件可以相对与另一个控件的上下左右方向上进行摆放,下图是B摆放在A的右边。

    <Button android:id="@+id/buttonA" ... />
             <Button android:id="@+id/buttonB" ...
                     app:layout_constraintLeft_toRightOf="@+id/buttonA" />
    
    01.png

    类似的属性有:

    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
    layout_constraintStart_toEndOf
    layout_constraintStart_toStartOf
    layout_constraintEnd_toStartOf
    layout_constraintEnd_toEndOf
    

    想要控件在父布局中居中,控件可以相对于parent,使用如下:

    <ImageView
            android:layout_marginTop="48dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:background="@color/colorAccent"
            android:layout_width="200dp"
            android:layout_height="48dp" />
    
    02.png

    除了简单的相对位置外,约束布局还支持角度方向的约束,如下图(1.1版本支持)。


    03.png

    A的中心可以相对B的中心在距离和角度上发生偏离。

    <Button android:id="@+id/buttonA" ... />
      <Button android:id="@+id/buttonB" ...
          app:layout_constraintCircle="@+id/buttonA"
          app:layout_constraintCircleRadius="100dp"
          app:layout_constraintCircleAngle="45" />
             
    
    布局链

    布局链类似于线性布局中的水平和竖直排列
    需要设置如下属性,即在水平或竖直方向上的布局链样式layout_constraintHorizontal_chainStyle 或layout_constraintVertical_chainStyle
    Chain Style有如下样式

    1. Spread :在水平或竖直方向上均匀分布,这个是默认属性
      通过图形化来创建链比较方便,动图如下


      约束布局.gif
    2. Spread inside:链头和链尾的控件的约束是固定的,中间的控件添加到链中之后会位于链的中间,即均匀分布。
    3. Weighted:类似于线性布局中的layout_weight属性,可以通过以下两个属性来调整控件在水平和竖直方向上的比例。
      layout_constraintHorizontal_weight 和 layout_constraintVertical_weight
      首先还是要创建链,然后设置宽度(高度)为0dp,再设置权重即可。
      约束布局.gif
      4.Packed:将链中的视图紧紧的放在一起(可以提供边距让其分开),然后让其居中在可用空间内
    Guideline(参考线)

    约束布局中参考线的作用和一些设计类工具中的参考线的作用是一致的,都是用来辅助设计的。
    可以通过图形化界面来创建参考线,当拖动到中间时会直接吸附过去,在界面中通常两边会有8dp的留白,这时可以通过建立参考线来实现控件的布局。


    约束布局.gif

    总结

    约束布局在使用体验上没有了过去相对布局和线性布局的多重嵌套,能够使视图树更加扁平,递归调用的深度更低,性能消耗更小。

    相关文章

      网友评论

        本文标题:ConstraintLayout简单使用

        本文链接:https://www.haomeiwen.com/subject/ehzxkftx.html