您的位置:首页 > 大数据 > 人工智能

ConstraintLayout约束布局学习笔记

2017-07-15 18:01 841 查看
声明:本文仅是个人学习总结笔记

参考文章:

张旭童ConstraintLayout 属性详解 和Chain的使用

http://www.jianshu.com/p/50debc330e91

郭神的Android新特性介绍,ConstraintLayout完全解析

http://blog.csdn.net/guolin_blog/article/details/53122387(可视化)

我对ConstraintLayout理解就是RelativeLayout相对布局的升级版,基本上可完全取代相对布局,而且和iOS中storyBoard中的AutoLayout有异曲同工之妙,下面总结的主要是与相对布局的异同点,方便自己查看。

属性值

属性名都形如layout_constraintXXX_toYYYOf

1、当XXX和YYY相同时,表示控件自身的XXX与约束控件的YYY的对齐

app:layout_constraintTop_toTopOf="@+id/btn_xxx"


表示当前控件的顶部与id为btn_xxx顶部对齐

2、当XXX和YYY相反时,表示控件自身的XXX在约束控件的YYY的一侧,

例如

app:layout_constraintLeft_toRightOf="@id/buttonA"


表示的是控件自身的左侧在buttonA的右侧

ID取值

1、子控件和子控件之间的约束

子控件和Guideline(新增的Guideline其实就是一个在屏幕上不显示的View,可用于辅助约束)的约束参数取值是 ID(@id/btn_xxx)(相对约束的控件ID,如:

app:layout_constraintTop_toTopOf="@+id/btn_xxx"


但如果是为了加链条的话,可能需要写成,详见链条部分

app:layout_constraintBottom_toTopOf="@+id/buttonB"


2、子控件和父控件的约束 是”parent”,如:

app:layout_constraintBottom_toBottomOf="parent"


Margins

1、margin和以往的使用一致,注意margin不能为负值

margin的方向需要和layout_constraintXXX_toYYYOf搭配使用

例如:

app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="100dp"


在相对布局中可以省略掉

app:layout_constraintTop_toTopOf="parent"


也能有margin效果,但是约束布局中不能省略

2、比相对布局多了一个属性layout_goneMarginXXX(xxx取值为start等等),此属性与 android:layout_marginXXX配合使用,“xxx”要一致,它在与之约束的控件消失(gone)的时候才会生效

尺寸约束

可以为ConstraintLayout 自身定义最小的尺寸,他会在 ConstraintLayout为WRAP_CONTENT时起作用。

android:minWidth
android:minHeight


用0dp意思是MATCH_CONSTRAINT。在指定方向,铺满约束里的区域,效果类似以前的MATCH_PARENT。其余用法跟以前一样。

android:layout_width="0dp"


上面代码会在水平方向约束条件内铺满

比例

以比例去定义View的宽高,需要将至少一个约束维度设置为0dp(即MATCH_CONSTRAINT,而且如果两个维度均设置为MATCH_CONSTRAINT(0dp),也可以使用比例。 在这种情况下,系统会使用满足所有约束条件和比率的最大尺寸。)

并将属性layout_constraintDimentionRatio设置为给定的比例。默认值是宽比高,如:

android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintDimensionRatio="3:1"


如果需要根据一个维度的尺寸去约束另一个维度的尺寸。

则可以在比率值的前面添加 W 或者 H 来分别约束宽度或者高度。H,表示高比宽。

上面的代码其实可看作

app:layout_constraintDimensionRatio="W,3:1"


链条(建议看原文)

简单说就是我中有你,你中有我,简单的代码

app:layout_constraintRight_toLeftOf="@+id/buttonB"
app:layout_constraintLeft_toRightOf="@+id/buttonA"


链条有头,水平链的头是链中最左边的View,垂直链的头是链中最顶端的View。

chainStyle只作用于头

在spread下才可以使用加权app:layout_constraintHorizontal_weight和app:layout_constraintVertical_weight

链条引用控件时,要注意”@+id/buttonB”和”@id/buttonB”的差别

<Button
android:id="@+id/buttonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ButtonA"
app:layout_constraintBottom_toTopOf="@+id/buttonB"
/>
<Button
android:id="@+id/buttonB"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="ButtonB"
app:layout_constraintTop_toBottomOf="@id/buttonA"
/>


上面如果写成了app:layout_constraintBottom_toTopOf=”@id/buttonB”编译是会报错的,提示

Error:(28, 46) No resource found that matches the given name (at 'layout_constraintBottom_toTopOf' with value '@id/buttonB').
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 约束布局