Android约束布局中心对齐两个文本字段

时间:2021-03-24 13:50:24

标签: android android-constraintlayout

我想将两个项目与另一个元素居中对齐,但我遇到了问题。

What I want to achieve

现在,如果我将顶部文本限制在左侧元素的顶部,将底部文本限制在左侧元素的底部并将它们链接起来。整个文本将移动。我想修复顶部文本元素,但如果文本较少,仍将其居中

答案尚未涵盖的另一个条件是,如果顶部文本有多于一行

enter image description here

1 个答案:

答案 0 :(得分:0)

在左侧视图的 50% 垂直标记处放置一个 Space。然后,您可以像这样将其他视图垂直约束到 Space

break

这看起来像下面的单行文本:

enter image description here

对于底部的多行文本TextView

enter image description here



为了解决注释问题,如果顶部 TextView 可以有不止一行并且只能向下移动,请添加带有 Space 和顶部 的结束屏障>TextView 作为引用的 id 如下:

<androidx.constraintlayout.widget.ConstraintLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/view"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginStart="16dp"
        android:background="#8BC34A"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Space
        android:id="@+id/space"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@id/view"
        app:layout_constraintStart_toEndOf="@id/view"
        app:layout_constraintTop_toTopOf="@id/view" />


    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginBottom="16dp"
        android:text="This is the upper TextView."
        app:layout_constraintBottom_toBottomOf="@+id/space"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:text="This is the lower TextView. This is the lower TextView. This is the lower TextView. This is the lower TextView. This is the lower TextView. This is the lower TextView. This is the lower TextView."
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/view"
        app:layout_constraintTop_toTopOf="@+id/space" />

</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here

enter image description here