You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置水平LinearLayout,让第二个TextView始终可见、第一个按需裁剪?

解决LinearLayout中TextView被挤出的问题

这个场景在Android水平线性布局里太常见了——当第一个文本内容过长时,直接把右侧的文本挤得看不见。要让第二个TextView始终可见,同时让第一个文本过长时自动裁剪,只需要调整几个关键属性就行,我给你修改后的完整代码,再逐个解释改动点:

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal">

    <ImageView 
        android:layout_width="20dp" 
        android:layout_height="20dp" 
        android:layout_margin="8dp" 
        android:background="@drawable/icon_place" />

    <TextView 
        android:layout_width="0dp"  <!-- 关键修改1:宽度设为0dp,配合权重分配空间 -->
        android:layout_height="wrap_content" 
        android:layout_margin="8dp" 
        android:maxLines="1" 
        android:ellipsize="end"  <!-- 关键修改2:添加省略号显示,让裁剪更友好 -->
        android:text="Information 1" 
        android:textColor="@android:color/black" 
        android:textSize="14sp" 
        android:textStyle="bold"
        android:layout_weight="1"/>  <!-- 关键修改3:设置权重,占据剩余可用空间 -->

    <TextView 
        android:layout_width="wrap_content"  <!-- 保持wrap_content,确保自身内容能显示 -->
        android:layout_height="wrap_content" 
        android:text="Information 2" 
        android:gravity="right" 
        android:textSize="13sp" 
        android:maxLines="1" 
        android:textColor="@android:color/darker_gray" 
        android:layout_margin="8dp"/>
</LinearLayout>

改动的核心逻辑:

  • 第一个TextView的layout_width="0dp" + layout_weight="1":LinearLayout水平布局中,权重会让这个TextView占据除了ImageView和第二个TextView之外的所有剩余空间,不会因为自身文本过长而无限扩张挤压其他控件。
  • 添加android:ellipsize="end":当文本长度超过分配的空间时,会在末尾显示省略号,提示用户文本被裁剪了,比直接截断更友好(你原来的代码只设置了maxLines=1,没有指定省略方式,所以可能只是生硬截断而没有提示)。
  • 第二个TextView保持layout_width="wrap_content":这样它会根据自身内容的宽度占用空间,确保始终能完整显示,不会被第一个TextView挤走。

这样修改后,不管第一个TextView的文本多长,右侧的第二个TextView都会稳稳待在原地,第一个文本则会自动裁剪并显示省略号~

内容的提问来源于stack exchange,提问作者Rob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:40:54