如何实现两个横向TextView总宽不足max_width左对齐,超宽时左侧省略?
实现方案
完全可以用单层ConstraintLayout实现该需求,无需嵌套两层布局,示例代码如下:
<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/container" android:layout_width="@dimen/max_width" android:layout_height="@dimen/some_height"> <TextView android:id="@+id/text1" android:layout_width="0dp" android:layout_height="match_parent" android:ellipsize="end" android:maxLines="1" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/text2" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintWidth_default="wrap" app:layout_constraintHorizontal_bias="0" app:layout_constraintHorizontal_chainStyle="packed" /> <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="match_parent" android:maxLines="1" app:layout_constraintStart_toEndOf="@id/text1" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性说明
app:layout_constraintWidth_default="wrap":text1默认适配内容宽度,当两个文本总宽度超出max_width时,text1的宽度会被自动压缩到最大可用空间,触发ellipsize属性显示末尾省略号,不会挤压text2的完整显示- 横向约束链+
packed样式+layout_constraintHorizontal_bias="0":两个文本总宽度不足max_width时整体靠左排列,右侧保留空白,完全符合你的需求场景
内容的提问来源于stack exchange,提问作者PuffySparrow
相关产品推荐
相关产品推荐

