ConstraintLayout实现View紧贴wrap_content控件且不超出父容器右侧
解决方案
问题核心是缺少右侧边界约束+未对nameText开启约束宽度限制,按照以下方式修改XML即可纯布局实现需求,无需编写动态修改属性的代码:
<?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:id="@+id/wrapper" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:background="#99776633" tools:ignore="MissingDefaultResource"> <TextView android:id="@+id/nameText" android:layout_width="0dp" android:layout_height="wrap_content" android:ellipsize="end" android:foreground="#66ff0000" android:maxLines="1" android:textSize="17sp" app:layout_constrainedWidth="true" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toLeftOf="@id/counter" app:layout_constraintTop_toTopOf="parent" app:layout_constraintWidth_default="wrap" tools:text="James BondJameames " /> <TextView android:id="@+id/counter" android:layout_width="wrap_content" android:layout_height="wrap_content" android:foreground="#9900fff0" android:maxLines="1" android:text="(47)" android:textSize="17sp" android:layout_marginLeft="1dp" app:layout_constraintLeft_toRightOf="@id/nameText" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
关键修改点说明
- 移除了多余的1dp宽seperator占位View,如需保留两个控件间的间距,直接给counter加
layout_marginLeft即可,减少不必要的布局层级 - 给
counter添加app:layout_constraintRight_toRightOf="parent"约束,强制它的右边界永远不超出父容器范围,同时把宽度从0dp改为wrap_content,保证它永远按自身内容宽度显示,不会被拉伸变形 - 给
nameText添加app:layout_constraintRight_toLeftOf="@id/counter"建立和counter的横向约束,同时添加app:layout_constrainedWidth="true"属性:该属性会让设置了layout_width="0dp"+layout_constraintWidth_default="wrap"的控件遵守约束边界,短文本时按内容宽度自适应,长文本时自动收缩到约束允许的最大宽度,触发尾部省略效果 - 把两个控件的高度从
0dp改为wrap_content,lines=1替换为maxLines=1,避免高度匹配父容器导致的显示异常,文字尺寸单位从dp改为标准的sp以适配系统字体缩放
最终效果
- 短文本场景:nameText按内容宽度显示,counter紧贴在nameText右侧,父容器左右边距正常
- 长文本场景:nameText自动在尾部显示省略号,counter始终完整显示在父容器边界内,不会被挤出
内容的提问来源于stack exchange,提问作者motis10
相关产品推荐
相关产品推荐

