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

如何实现Android计算器界面中单行、溢出省略、可横向滑动的TextView

解决方案

问题原因

  • 废弃属性android:singleLine和高版本Android的大字号、右对齐配置存在兼容bug,会导致初始内容无法渲染
  • 仅配置android:maxLines="1"未开启横向滚动属性时,内容宽度超过控件宽度会默认触发换行逻辑,导致展示多行

修改方案

1. XML布局调整

修改你的TextView配置如下,核心新增android:maxLines="1"和android:scrollHorizontally="true"属性,移除废弃的android:singleLine:

<TextView
        android:id="@+id/tvInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:ellipsize="start"
        android:gravity="end"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:scrollbars="horizontal"
        android:text="@string/num0"
        android:textColor="@color/black"
        android:textSize="80sp"
        <!-- 新增以下两个属性 -->
        android:maxLines="1"
        android:scrollHorizontally="true" />

2. Activity代码保留原有配置即可

tvInput.movementMethod = ScrollingMovementMethod.getInstance()

效果验证

  • 内容长度小于控件宽度时,正常右对齐显示初始内容0
  • 内容长度超出控件宽度时,左侧自动补充...,不会触发换行
  • 手指横向滑动TextView可查看完整的计算公式内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:39:03