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

如何让横向LinearLayout中的两个TextView自动适配以最大化显示内容?

解决横向LinearLayout双TextView自适应空间并省略截断的问题

我来给你分享个实用的实现方案,完全贴合你想要的效果:

核心布局逻辑

要让两个TextView根据内容长短灵活分配屏幕空间,关键在于结合LinearLayout的权重机制,再配合TextView的文本截断属性,同时设置最小宽度避免某一侧被过度压缩。

可直接复用的布局代码

直接上能跑的XML代码,复制过去就能测试:

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

    <!-- 左侧文本 -->
    <TextView
        android:id="@+id/tv_left"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ellipsize="end"
        android:maxLines="1"
        android:minWidth="80dp" <!-- 防止内容过短时被挤没 -->
        android:text="Short"
        android:textSize="16sp"/>

    <!-- 分隔符 | -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" | "
        android:textSize="16sp"/>

    <!-- 右侧文本 -->
    <TextView
        android:id="@+id/tv_right"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ellipsize="end"
        android:maxLines="1"
        android:minWidth="80dp"
        android:text="LongLongLongLongLongLongLong"
        android:textSize="16sp"/>

</LinearLayout>

效果对应说明

  • 双短文本场景:比如Short | Short,两个TextView会平分可用空间,完整显示文本,呈现你要的Short | Short效果。
  • 一短一长场景:比如Short | LongLongLongLong...,短文本侧保持最小宽度,长文本侧占据剩余所有空间,超出部分自动用省略号截断,得到Short | Long...的结果。
  • 双超长文本场景:两个TextView会平分屏幕空间,各自超出部分用省略号截断,比如LongLo... | LongLo...。

额外优化小技巧

  • 如果想让某一侧优先占据更多空间,可以调整layout_weight的数值,比如左侧设为2、右侧设为1,这样左侧会先拿到2/3的空间,剩余部分给右侧。
  • minWidth可以根据你的实际需求调整,确保文本不会被压缩到完全不可见。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:10:49