首页 > 解决方案 > 在 ConstraintLayout 中垂直居中 2 个视图

问题描述

我有 2 个视图需要垂直居中(两者)。我需要在 2 个视图之间固定上边距 (40 dp) 如何使用 ConstraintLayout 来做到这一点?

谢谢。

标签: androidandroid-constraintlayout

解决方案


您需要使用链,在这种情况下app:layout_constraintVertical_chainStyle="packed"将实现您正在寻找的东西。

尝试这样的事情:

<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">

    <TextView
        android:id="@+id/text_view_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView 1"
        app:layout_constraintBottom_toTopOf="@+id/text_view_2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <TextView
        android:id="@+id/text_view_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="TextView 2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text_view_1" />
</androidx.constraintlayout.widget.ConstraintLayout>

推荐阅读