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

LinearLayout中两个TextView并列显示双向不被截断的实现方法

需求说明

在LinearLayout中放置两个TextView,需满足二者尽可能占满布局可用空间同时互不被截断。

初始实现及问题

最初尝试通过设置minWidth限制最小宽度,但发现layout_weight属性会忽略该配置,初始代码如下:

<TextView
        android:id="@+id/textOrigin"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:ellipsize="end"
        android:maxLines="1"
        android:layout_weight="1"
        android:minWidth="170dp" /> <!-- 此处minWidth配置不生效 -->

<TextView
        android:id="@+id/textDestination"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:ellipsize="end"
        android:maxLines="1"
        android:layout_weight="0"
        android:gravity="end"/>

上述代码存在的问题:第二个TextView内容过长时,wrap_content宽度会挤占第一个TextView的显示空间,无法满足双向不被截断的需求。

预期显示场景

需同时满足以下三种显示场景:

|<TextView>......<TextView>| --> 无截断,正常显示
|<TextViewcanbeverylong...><TextView>| --> 左侧文本过长时,右侧保留最小宽度,左侧文本末尾省略
|<TextView><TextViewcanbeverylongtoo...>| --> 右侧文本过长时,左侧保留最小宽度,右侧文本末尾省略
最终解决方案

将两个TextView的layout_width都设置为wrap_content,同时设置相同的layout_weight和minWidth即可让minWidth配置生效,实现上述需求,代码如下:

<TextView
        android:id="@+id/textOrigin"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:ellipsize="end"
        android:maxLines="1"
        android:layout_weight="1"
        android:minWidth="170dp"/>

<TextView
        android:id="@+id/textDestination"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:ellipsize="end"
        android:maxLines="1"
        android:layout_weight="1"
        android:minWidth="170dp"
        android:gravity="end"/>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 05:57:02