在屏幕上居中放置TextView,但不与其他视图重叠

问题描述 投票:0回答:1

在我的应用程序中,我有一个ConstraintLayout,我想在其中将TextView放在屏幕中央。通常我会这样:

<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="Example Text" />

</androidx.constraintlayout.widget.ConstraintLayout>

但是现在让我们说TextView的每一侧都有两个宽度不同的视图。我的问题是我不希望TextView的文本与侧面的视图重叠,同时将其保留在屏幕中间。我应该怎么做?

android android-constraintlayout
1个回答
0
投票

尝试一下

    <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:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toStartOf="@id/tvCenter"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Example Text" />

        <TextView
            android:id="@+id/tvCenter"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Example Text" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toEndOf="@id/tvCenter"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="Example Text" />

    </androidx.constraintlayout.widget.ConstraintLayout>

但是您需要确保tvCenter的长度小于屏幕宽度。否则,您需要为其设置maxHeight

© www.soinside.com 2019 - 2024. All rights reserved.