ConstraintLayout 作为 Android Studio 的默认布局,能有效减少布局层级并提升渲染性能。它通过约束关系灵活定位和调整子 View 的大小,理解其机制对构建高效界面至关重要。
基础约束属性
ConstraintLayout 的核心在于 layout_constraintXXX_toYYYOf 格式的属性,用于定义 View A 相对于 View B(或父容器 parent)的位置关系。常见的对齐方式包括左右、上下及基线对齐:
layout_constraintBaseline_toBaselineOf:文字基线对齐layout_constraintLeft_toLeftOf/Right_toRightOf:左右边界对齐layout_constraintTop_toTopOf/Bottom_toBottomOf:上下边界对齐layout_constraintStart_toEndOf/End_toStartOf:支持 RTL 布局的起始/结束对齐
若某个方向缺少约束,控件将不会在该方向上居中。例如,仅设置顶部约束的 View 会紧贴顶部,而同时设置上下约束且强度一致时,View 会自动垂直居中。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">
<TextView
android:id="@+id/tv1"
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_margin="20dp"
android:background="#f5ec7e"
android:gravity="center"
android:text="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf=
= />

