ConstraintLayout使用详解

ConstraintLayout 是 Android Studio 2.2 中主要的新增功能之一,也是 Google 在2016 年的 I/O 大会上重点宣传的一个功能。ConstraintLayout 是使用约束的方式来指定各个控件的位置和关系的,相比 RelativeLayout 和 LineatLayout 具有更强的特性,可以减少布局之间的嵌套。

1. 添加 ConstraintLayout

在工程app目录下的 build.gradle 添加如下:

dependencies {
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
}

2. 相对位置属性

layout_constraint[自身控件位置]_[目标控件位置]="[目标控件ID]",如果id是父布局的id,可以使用parent

ConstraintLayout使用详解_第1张图片
ConstraintLayout使用详解_第2张图片

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

3. Margin属性

ConstraintLayout使用详解_第3张图片

android:layout_marginStart
android:layout_marginEnd
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom

4. goneMargin属性

goneMargin属性是指目标控件GONE掉之后,自身控件可以设置个margin值。不过margin的方向需要和控件的相对位置的方向保持一致。

假设我们有这样一个需求:A设置为gone后,B需要距离父布局的左侧200dp,怎么办?这时候,goneMargin属性就派上用场啦,只要设置B的layout_goneMarginLeft=200dp即可。这样,A为gone时,B距离父布局左侧200dp。

layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom

5. Bias属性

bias属性是指在对齐父容器后,设置水平与竖直的比例。bias支持的属性如下:

layout_constraintHorizontal_bias
layout_constraintVertical_bias


             

运行图,如下:

ConstraintLayout使用详解_第4张图片

7. Chains 链状结构

如下图:

ConstraintLayout使用详解_第5张图片

要想Chain Style生效,必须设置当前链方向的边为wrap_content,比如上面的水平链,宽设为wrap_content。还有就是控件要相互引用,比如A的右边依赖B的左边,B的左边依赖A的右边。

Chain Style 设置在第一个控件上 。

属性有两个:

layout_constraintHorizontal_chainStyle
layout_constraintVertical_chainStyle

支持的值有三个:

CHAIN_SPREAD:均匀分布控件。
CHAIN_SPREAD_INSIDE,同上,但是边上的控件不均匀分布。
CHAIN_PACKED:控件紧挨在一起,还可以通过bias属性设置偏移量。

ConstraintLayout使用详解_第6张图片

Weighted chains:

app:layout_constraintHorizontal_weight
app:layout_constraintVertical_weight

跟线性布局的weight差不多,layout_constraintHorizontal_weight需要设置width=0dp,控件的大小根据设置的weight比例进行设置。




    

    

    



运行图,如下:

ConstraintLayout使用详解_第7张图片

8. Guideline

android.support.constraint.Guideline 该类比较简单,主要用于辅助布局,即类似为辅助线,横向的、纵向的。该布局是不会显示到界面上的。

所以其有个属性为:

android:orientation="vertical"
android:orientation="horizontal"

除此以外,还差个属性,决定该辅助线的位置:

layout_constraintGuide_begin
layout_constraintGuide_end
layout_constraintGuide_percent

可以通过上面3个属性其中之一来确定属性值位置。

begin=30dp,即可认为距离顶部30dp的地方有个辅助线,根据orientation来决定是横向还是纵向。
end=30dp,即为距离底部。
percent=0.8即为距离顶部80%。

比如:有个按钮,决定通过两根辅助线来定位,一根横向距离底部80%,一个纵向距离顶部80%,按钮就定位在他们交叉的地方。



    

    

    


运行图,如下:

ConstraintLayout使用详解_第8张图片
  • 注意ConstraintLayout不支持match_parent属性,要用0dp代替,在加上设置特性的约束属性,即可实现match_parent的效果。

ConstraintLayout官方文档

你可能感兴趣的:(ConstraintLayout使用详解)