gpt4 book ai didi

java - 为什么 String.format() 在 Android TextView 上不起作用?

转载 作者:太空宇宙 更新时间:2023-11-03 12:08:44 25 4
gpt4 key购买 nike

我正在尝试格式化 Android TextView 上的文本。这是我在 Java 控制台中尝试的代码:

System.out.println(String.format("%-7s 56", "S"));
System.out.println(String.format("%-7s 56", "A(102)"));

输出是预期的,我的文本是左对齐的:

S       56
A(102) 56

不,我在 Android TextView 上尝试相同的代码:

mTextView.setText(String.format("%-7s 56\n", "S"));
mTextView.append(String.format("%-7s 56", "A(102)"));

这是结果:

enter image description here

如您所见,输出不是预期的文本未对齐。我做错了什么?还有其他方法吗?

最佳答案

问题是我没有使用等宽字体。

A monospaced font, also called a fixed-pitch, fixed-width or non-proportional font, is a font whose letters and characters each occupy the same amount of horizontal space

所以我只在写入 TextView 之前添加了这一行:

mTextView.setTypeface(Typeface.MONOSPACE);

关于java - 为什么 String.format() 在 Android TextView 上不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18678709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com