首页 > 解决方案 > 一个 Textview 在 ConstraintLayout 中与另一个重叠

问题描述

我有 ConstraintLayout,里面有两个 TextView:

<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="wrap_content">
    <TextView
        android:id="@+id/first"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <TextView
        android:id="@+id/second"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/first"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>

我想将第一个放在父容器的左上角,并将第二个放在父容器的右上角。但是两个文本视图都可以包含任意长度的文本。当第一个文本很长时,它会与第二个文本视图重叠。我可以通过在 LinearLayout 中包装两个文本视图来解决这个问题。但这种方式在我看来并不优雅。也许还有另一种方法可以做到这一点?我的意思是 ConstraintLayout 的功能

标签: androidandroid-constraintlayout

解决方案


首先,wrap_content从你的宽度中删除,因为这使得左/右约束无关紧要。在其位置使用0dp以使其遵守约束规则。

然后在视图之间创建一个水平链并将其设置为spread,以便视图在任何点都不会重叠,并且它们也始终停留在屏幕的边缘。

最后,相应地对齐文本,使左侧对齐到视图的开头,右侧对齐到末尾。在下面的示例中,您会看到无论文本有多长,视图都不会重叠并粘在它们的两侧。

注意:为了适应具有不同文本方向的设备,使用开始/结束约束(如在我的代码中)而不是左/右被认为是更好的做法。您还可以通过添加适当的边距来修改下面的代码,使文本远离屏幕边缘。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/first"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAlignment="viewStart"
        app:layout_constraintEnd_toStartOf="@+id/second"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="@tools:sample/lorem/random" />

    <TextView
        android:id="@+id/second"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAlignment="viewEnd"
        app:layout_constrainedWidth="true"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintStart_toEndOf="@id/first"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="@tools:sample/lorem/random" />

</androidx.constraintlayout.widget.ConstraintLayout>

在此处输入图像描述


推荐阅读