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

Kotlin中TextView显示菱形文本时空格丢失问题求助

问题:TextView显示菱形图案时空格消失

我用Kotlin编写了一个生成菱形图案的函数,将生成的图案存入变量后传递给TextView显示。日志显示变量中包含空格,但TextView显示时空格消失,其余内容正常。

生成菱形的函数代码

fun printDiamond(n: Int): String {

    for (i in -n..n) {
        for (j in -n - 1..n + 1)
            if (j == 0) {
                str = res
                res = str
            }
            else if (abs(j) == n + 1)
                if (abs(i) == n){
                    str = "$res+"
                    res = str
                }
                else{
                    str = "$res|"
                    res = str
                }
            else if (abs(i) == n){
                str = "$res-"
                res = str
            }
            else if (i == 0 && j == -n){
                str = "$res<"
                res = str
            }
            else if (i == 0 && j == n){
                str = "$res>"
                res = str
            }
            else if (abs(i - j) == n){
                str = "$res\\"
                res = str
            }
            else if (abs(i + j) == n){
                str = "$res/"
                res = str
            }
            else if (abs(i) + abs(j) < n)
                if ((n - i) % 2 != 0){
                    str = "$res="
                    res = str
                }
                else{
                    str = "$res-"
                    res = str
                }
            else{
                str = "$res "
                res = str
            }
        str = "$res\n"
        res = str
    }
    Log.d("Process", "Return =\n$res")
    return res
}

显示代码

selected = dropdown.selectedItem.toString()
logic = com.example.mobile_lab1.Lab1.Process().printDiamond(selected.toInt())
Log.d("Process", "Logic =\n$logic")
textValue.text = selectedtext.text = logic

解决办法

原因

TextView默认会合并连续空格,并且对单个空格进行压缩处理,导致图案中的空格无法正常显示。

方案1:替换普通空格为非断空格

修改生成函数中添加空格的代码,把普通空格" "换成Unicode非断空格\u00A0:

else{
    str = "$res\u00A0"
    res = str
}

方案2:配置TextView属性

在布局文件中给TextView添加以下属性:

android:singleLine="false"
android:inputType="textMultiLine"
android:typeface="monospace"
  • singleLine="false":允许多行显示
  • inputType="textMultiLine":开启多行文本模式,保留空格格式
  • typeface="monospace":使用等宽字体,让菱形图案的对齐更规整

方案3:使用HTML格式显示

将字符串中的空格替换为&nbsp;,然后通过Html工具类转换后设置给TextView:

val formattedLogic = logic.replace(" ", "&nbsp;")
textValue.text = Html.fromHtml(formattedLogic, Html.FROM_HTML_MODE_LEGACY)

注意:Android 7.0(API 24)及以上版本需要使用Html.FROM_HTML_MODE_LEGACY,低版本直接用Html.fromHtml(formattedLogic)即可。

内容的提问来源于stack exchange,提问作者Игнат Тимофеев

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 13:27:52