【发布时间】:2020-05-08 15:44:58
【问题描述】:
我需要有一个单行 TextView 在其父 ConstraintLayout 内居中,但不能与同一布局内的其他视图重叠,以便在末尾广告 ... 省略号
ConstraintLayout (height: 48dp, width: match_parent) 包含以下3个子view:
- 左锚定容器(高度:48dp,宽度:可变 - 下图中的绿色)
- TextView(以 ConstraintLayout 为中心)
- 右锚定容器(高度:48dp,宽度:可变 - 下图中的蓝色)
左/右容器的宽度不相等(一个可以为 0,另一个为 48dp,或者一个为 48dp,另一个为 96dp)
XML 布局如下所示:
<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="48dp"
android:background="#FF0000">
<LinearLayout
android:id="@+id/container_start"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#00FF00"
android:orientation="horizontal"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
<TextView
android:id="@+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="@id/container_start"
app:layout_constraintEnd_toStartOf="@id/container_end"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:maxLines="1"
android:ellipsize="end"
android:text="Title Title Title Title" />
<LinearLayout
android:id="@+id/container_end"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#0000FF"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
- 如果我将 TextView 锚定到父级(左/右),它将居中,但文本会与侧容器重叠
- 如果我将 TextView 锚定到侧面容器,文本不会重叠,但如果容器具有不同的宽度,它可能不会居中。
【问题讨论】:
-
你为什么在
TextView的每一边都使用LinearLayouts? -
@COYG 视图将在代码中添加到这些容器中。这是标题栏的布局,因此左/右容器将包含按钮,可能左侧 1 和右侧 2,反之亦然
标签: android android-layout android-constraintlayout