ConstraintLayout进阶使用

120 阅读1分钟

这是我参与11月更文挑战的第4天,活动详情查看:2021最后一次更文挑战

简介

ConstraintLayout 可让您使用扁平视图层次结构(无嵌套视图组)创建复杂的大型布局。它与 RelativeLayout 相似,其中所有的视图均根据同级视图与父布局之间的关系进行布局,但其灵活性要高于 RelativeLayout,并且更易于与 Android Studio 的布局编辑器配合使用。

背景

在项目中经常有比较复杂的布局, 甚至有些布局使用RelativeLayout或者LinearLayout会使层次嵌套的比较深, 会大大的影响UI渲染的速度. 这个时候使得UI的性能优化显得尤为重要

项目实战

在项目中经常有两个或者多个控件整体居中的布局, 如果使用基础控件来做就比较麻烦, 如果使用ConstraintLayout来做就比较简单

使用

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white">
    <Button
        android:id="@+id/btn_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="15dp"
        android:background="@color/green"
        android:text="居上"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@id/btn_center"
        app:layout_constraintLeft_toLeftOf="@id/btn_center"
        app:layout_constraintVertical_chainStyle="spread" />

    <Button
        android:id="@+id/btn_center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/green"
        android:text="居中"
        app:layout_constraintBottom_toTopOf="@+id/btn_bottom"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_top"/>

    <Button
        android:id="@+id/btn_bottom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:background="@color/green"
        android:text="居下"
        app:layout_constraintRight_toRightOf="@id/btn_center"
        app:layout_constraintTop_toBottomOf="@id/btn_center"
        app:layout_constraintBottom_toBottomOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

spread 效果

image.png

packed 效果

image.png

spread_inside 效果

image.png

配合权重使用

注意: 如果要配合权重使用 layout_height需要设置为0dp

app:layout_constraintVertical_weight="1"

image.png

常用属性

app:layout_constraintVertical_chainStyle可选值为spread平分屏幕并居中,packed把所有控件作为一个整体居中,spread_inside两边的控件分别对齐父布局, 中间的控件平分屏幕