在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
12345
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我认为它将删除第三个字符,例如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/