布局需求实现:标题视图扩展时如何让日期视图保持原有尺寸
解决方案:实现标题自适应省略+日期固定宽度不被挤压
我明白你要的效果——标题左对齐、能占满除了日期之外的剩余空间,内容超长时末尾自动省略;日期始终在标题右侧,哪怕标题内容再长也能保持自身宽度不被省略对吧?之前做列表项布局的时候经常碰到这个需求,下面给你两种常用的实现方式:
方式一:用LinearLayout快速实现
这种方式适合布局结构比较简单的场景,核心是利用layout_weight让标题抢占剩余空间:
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center_vertical"> <!-- 标题TextView:占满剩余空间,超长时省略 --> <TextView android:id="@+id/tv_title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:ellipsize="end" android:maxLines="1" android:text="这是一段非常非常长的标题内容用来测试省略效果的示例文本" android:textSize="16sp"/> <!-- 日期TextView:保持自身宽度,不被挤压 --> <TextView android:id="@+id/tv_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="2024-05-20" android:textSize="14sp"/> </LinearLayout>
关键要点:
- 标题的
layout_width设为0dp,搭配layout_weight="1",这样它会自动填充除了日期之外的所有水平空间 - 必须给标题设置
android:maxLines="1"和android:ellipsize="end",否则超长时不会触发省略效果 - 日期用
wrap_content确保宽度自适应自身内容,不会被挤压变形或省略
方式二:用ConstraintLayout实现更灵活的布局
如果你的布局本身就是用ConstraintLayout构建的,这种方式更适配整体结构:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/tv_title" android:layout_width="0dp" android:layout_height="wrap_content" android:ellipsize="end" android:maxLines="1" android:text="这是一段非常非常长的标题内容用来测试省略效果的示例文本" android:textSize="16sp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@+id/tv_date" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0"/> <!-- 强制左对齐 --> <TextView android:id="@+id/tv_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="2024-05-20" android:textSize="14sp" app:layout_constraintStart_toEndOf="@+id/tv_title" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键要点:
- 标题的
layout_width设为0dp,通过约束start到父布局、end到日期的start,让它填充两者之间的所有空间 layout_constraintHorizontal_bias="0"确保标题始终左对齐,不会因为空间变化居中或右移- 日期的约束
start到标题的end、end到父布局,同时宽度设为wrap_content,保证自身内容完整显示
这两种方式都能完美实现你要的效果,你可以根据自己的布局结构选择合适的方案~
内容的提问来源于stack exchange,提问作者Victor Manuel Pineda Murcia
相关产品推荐
相关产品推荐

