Reputation: 51
In an Android application I have a field where the user should type some 14-digits number like 12345678901234. I want this number to look like 12 3456 7890 1234. I've tried to do this by code:
if((s.length() == 2 || s.length() == 7 || s.length() == 12)){
s.insert(s.length(), " ");
}
But when the user starts to type in the middle of the text, my code works wrong.
I've tried to use the DecimalFormat class:
DecimalFormat decimalFormat = new DecimalFormat("##,####.#### ####");
String formattedText = decimalFormat.format(Double.parseDouble(etContent.getText().toString()));
but I receive an IllegalArgumentException.
Any ideas how to do that?
P.S The main problem is I should format text "right now" like:
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
Upvotes: 1
Views: 205
Reputation: 402
Try these codes in TextWatcher.afterTextChanged(Editable)
@Override
public void afterTextChanged(Editable s) {
if (changeText) {
Log.d("afterTextChanged", "afterTextChanged");
String txt = s.toString();
txt = txt.replaceAll("\\s+", "");
changeText = false;
s.clear();
int index = 0;
for (char c:txt.toCharArray()) {
if (index == 2
|| index == 7
|| index == 12) {
s.append(' ');
index++;
}
s.append(c);
index++;
}
changeText = true;
}
}
changeText is a boolean tag that prevent infinite loop.
Upvotes: 0
Reputation: 1768
Simply use the substring method:
String formattedText = s.substring(0,2) + " " + s.substring(2,6)+
" " + s.substring(6,10) + " " + s.substring(10,14);
Upvotes: 0
Reputation: 2303
@Karthika PB I think it will remove the 3rd character i.e 12 4567 like it will come. Try this
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);
}
Upvotes: 1
Reputation: 1373
try this remove white spaces and insert space
String seq=etContent.getText().toString().trim();//to remove white spaces
String newstring="";
for(int i=0;i<seq.length();i++){
if(i==2 || i==7 || i==14){
newstring=newstring+" ";
}
else
newstring=newstring+seq.charAt(i);
}
use newstring which will have the formatted text
Upvotes: 0