ConstraintLayout的简单使用

217 阅读2分钟

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

简介

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

背景

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

导入依赖

  • 添加声明 在根目录的build中声明Google
repositories {
        google()
    }
  • 导入依赖
implementation "androidx.constraintlayout:constraintlayout:2.1.1"
    // To use constraintlayout in compose
    implementation "androidx.constraintlayout:constraintlayout-compose:1.0.0-rc01"

简单使用

按照一般使用Layout方法进行排版button会报错

This view is not constrained. It only has designtime positions, so it will jump to (0,0) at runtime unless you add the constraints 意思是说这个视图没有添加约束, 你必须添加约束才可以正常使用

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:background="@color/white"
    android:layout_height="match_parent">
    <Button
        android:layout_width="wrap_content"
        android:text="左上"
        android:background="@color/green"
        android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>
  • 添加约束

PS: 必须至少指定X轴和Y轴才可以正常使用

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/white"
    android:layout_height="match_parent">
    <Button
        android:layout_width="wrap_content"
        android:text="左上"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:background="@color/green"
        android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>

实际使用

image.png

image.png

常用属性

app:layout_constraintTop_toTopOf控件的顶部和目标顶部对齐,可以设置的值为parent或者目标控件的id app:layout_constraintBottom_toBottomOf控件的底部与目标的底部对齐,可以设置的值为parent或者目标控件的id app:layout_constraintLeft_toLeftOf控件的左边与目标的左边对齐,可以设置的值为parent或者目标控件的id app:layout_constraintRight_toRightOf控件的右边与目标的右边对齐,可以设置的值为parent或者目标控件的id