Один Textview перекрывает другой в ConstraintLayout - PullRequest
0 голосов
/ 01 ноября 2019

У меня есть 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

Ответы [ 6 ]

1 голос
/ 01 ноября 2019

Прежде всего, удалите wrap_content из вашей ширины, так как это делает ограничения влево / вправо неактуальными. Вместо него используйте 0dp, чтобы придерживаться правил ограничений.

Затем создайте горизонтальную цепочку между представлениями и получите spread, чтобы представления не перекрывались ни в одной точке, а также всегда оставались на краях экрана.

Наконец, выровняйте тексты соответствующим образом, чтобы левый выравнивался по началу просмотра, а правый - по концу. В приведенном ниже примере вы видите, что независимо от длины текста представления не перекрываются и не смещаются по сторонам.

ПРИМЕЧАНИЕ: Лучше использовать start /Конечные ограничения (как в моем коде) вместо левого / правого, чтобы обслуживать устройства с другим направлением текста. Вы также можете изменить приведенный ниже код, добавив соответствующие поля, чтобы текст находился дальше от краев экрана.

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

enter image description here

0 голосов
/ 01 ноября 2019
 <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

          <androidx.appcompat.widget.AppCompatTextView
                    android:id="@+id/tvFirst"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    app:layout_constraintEnd_toStartOf="@+id/tvSecond"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <androidx.appcompat.widget.AppCompatTextView
                    android:id="@+id/tvSecond"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toEndOf="@+id/tvFirst"
                    app:layout_constraintTop_toTopOf="parent" />

            </androidx.constraintlayout.widget.ConstraintLayout>
0 голосов
/ 01 ноября 2019
<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="0dp"
        app:layout_constraintRight_toLeftOf="@+id/second"
        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="0dp"
        android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>
0 голосов
/ 01 ноября 2019
<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:gravity="right"
        android:layout_width="0dp"
        android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>

Таким образом, второй TextView наверняка не будет перекрывать первый, но может случиться так, что первый слишком длинный, и для второго места нет места. В таком случае я бы порекомендовал установить maxWidth для первого TextView, чтобы в худшем случае оставалось место для второго TextView.

Также я добавил гравитацию ко второму, чтобы текст оставался справа отTextView.

0 голосов
/ 01 ноября 2019

Попробуйте код ниже, это может быть полезно для вас: -

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
tools:context=".MainActivity">



    <TextView
        android:layout_alignParentLeft="true"
        android:id="@+id/first"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:text="abc"
        android:layout_margin="@dimen/dp_5"
        android:layout_alignParentStart="true" />
    <TextView
        android:id="@+id/second"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toRightOf="@+id/first"
        android:layout_toRightOf="@+id/first"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/dp_5"
        android:text="xyz"
         />

 </RelativeLayout>
0 голосов
/ 01 ноября 2019

используйте это

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