在 Android 应用程序中,我有一个字段,用户应在其中输入一些 14 位数字,例如 12345678901234。 我希望这个数字看起来像 12 3456 7890 1234。 我试图通过代码来做到这一点:
if((s.length() == 2 || s.length() == 7 || s.length() == 12)){
s.insert(s.length(), " ");
}
但是当用户开始在文本中间输入时,我的代码就出错了。
我尝试使用 DecimalFormat 类:
DecimalFormat decimalFormat = new DecimalFormat("##,####.#### ####");
String formattedText = decimalFormat.format(Double.parseDouble(etContent.getText().toString()));
但我收到 IllegalArgumentException。
任何想法如何做到这一点?
P.S 主要问题是我应该“立即”格式化文本,例如:
1
12
12 3
12 34
12 345
12 3456
12 3456 7
12 3456 78
12 3456 789
12 3456 7890
12 3456 7890 1
12 3456 7890 12
12 3456 7890 123
12 3456 7890 1234
最佳答案
@Karthika PB 我认为它将删除第 3 个字符,即 12 4567,就像它会出现一样。 试试这个
String seq = editText.getText().toString().trim();
String newstring = "";
for (int i = 0; i < seq.length(); i++) {
if (i == 2 || i == 6 || i == 10) {
newstring = newstring + " " + seq.charAt(i);
} else
newstring = newstring + seq.charAt(i);
}
关于java - 如何按空格格式化文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510842/