如何用ConstraintLayout实现单行TextView在两小图间的适配布局?
解决方案
要同时满足文本短时居中、文本长时自动截断且图片始终可见的需求,你需要调整ConstraintLayout的约束链和TextView的宽度属性,具体修改如下:
核心修改点
- 为左图、TextView、右图设置水平约束链,并将链样式设为
packed,实现文本短时整体居中 - 给TextView添加
android:ellipsize="end",确保文本过长时显示省略号 - 调整TextView的宽度为
wrap_content并开启layout_constrainedWidth="true",让文本过长时自动压缩到可用空间,同时保证图片不被挤压 - 给左右ImageView添加适当margin,避免与TextView紧贴
修改后的完整布局代码
<?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="wrap_content" android:paddingHorizontal="8dp"> <ImageView android:id="@+id/image_left" android:layout_width="16dp" android:layout_height="16dp" android:src="@drawable/circle" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/centered_text" app:layout_constraintHorizontal_chainStyle="packed" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintHorizontal_bias="0.5" app:tint="@color/red" android:layout_marginEnd="8dp"/> <TextView android:id="@+id/centered_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="end" app:layout_constrainedWidth="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@id/image_right" app:layout_constraintStart_toEndOf="@id/image_left" app:layout_constraintTop_toTopOf="parent" tools:text="some weird message that is too long to fit in the screen and will be truncated"/> <ImageView android:id="@+id/image_right" android:layout_width="16dp" android:layout_height="16dp" android:src="@drawable/circle" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toEndOf="@id/centered_text" app:layout_constraintTop_toTopOf="parent" app:tint="@color/red" android:layout_marginStart="8dp"/> </androidx.constraintlayout.widget.ConstraintLayout>
效果说明
- 文本较短时:水平约束链的
packed样式会让三个控件整体居中,TextView以内容宽度展示,左右图片紧贴TextView两侧 - 文本较长时:
layout_constrainedWidth="true"会限制TextView的最大宽度为父布局宽度减去左右图片宽度和margin,文本自动截断并显示省略号,同时左右图片始终保持在父布局边界内,完整可见
内容的提问来源于stack exchange,提问作者Pavel Startsev
相关产品推荐
相关产品推荐

