I have an EditText and a TextWatcher.
Skeleton of my code:
EditText x;
x.addTextChangedListener(new XyzTextWatcher());
XyzTextWatcher implements TextWatcher() {
public synchronized void afterTextChanged(Editable text) {
formatText(text);
}
}
My formatText() method inserts some hyphens at some positions of the text.
private void formatText(Editable text) {
removeSeparators(text);
if (text.length() >= 3) {
text.insert(3, "-");
}
if (text.length() >= 7) {
text.insert(7, "-");
}
}
private void removeSeparators(Editable text) {
int p = 0;
while (p < text.length()) {
if (text.charAt(p) == '-') {
text.delete(p, p + 1);
} else {
p++;
}
}
}
The problem I have is - what is displayed on my EditText isn't in sync with the Editable. When I debugged the code, I saw that the variable text (Editable) has the expected value, but what's shown on the EditText doesn't always match the Editable.
For example, when I have a text
x = "123-456-789"
I cut the text "456" from x manually.
After formatting, my Editable has the value "123-789-"
However, the value shown on my EditText is "123--789"
They have the same value in most cases though.
I assumed that the EditText IS the Editable and they should always match. Am I missing something?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…