問題描述
我有一個 EditText 和一個 TextWatcher.
I have an EditText and a TextWatcher.
我的代碼骨架:
EditText x;
x.addTextChangedListener(new XyzTextWatcher());
XyzTextWatcher implements TextWatcher() {
public synchronized void afterTextChanged(Editable text) {
formatText(text);
}
}
我的 formatText() 方法在文本的某些位置插入一些連字符.
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++;
}
}
}
我遇到的問題是 - 我的 EditText 上顯示的內容與 Editable 不同步.當我調試代碼時,我看到變量 text (Editable) 具有預期值,但 EditText 上顯示的內容并不總是與 Editable 匹配.
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.
例如,當我有一個文本x = "123-456-789"我手動從 x 中剪切了文本456".格式化后,我的 Editable 的值為123-789-"但是,我的 EditText 上顯示的值是123--789"
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.
我假設 EditText 是 Editable 并且它們應該始終匹配.我錯過了什么嗎?
I assumed that the EditText IS the Editable and they should always match. Am I missing something?
推薦答案
好吧,你從來沒有真正改變 EditText 只是 Editable.Android EditTexts 不是 Editable 類的子級.字符串是 Editable 類的子類.onTextChangedListener 不接收 EditText 作為參數,而是接收 EditText 中顯示的 Editable/String.使用連字符格式化 Editable 后,您需要更新 EditText.這樣的事情應該可以正常工作:
Ok, you never actually change the EditText just the Editable. Android EditTexts are not children of the Editable class. Strings are subclasses of the Editable class. The onTextChangedListener doesn't receive the EditText as an argument but the Editable/String displayed in the EditText. After you format the Editable with the hyphens you then need to update the EditText. Something like this should work fine:
class MyClass extends Activity{
//I've ommited the onStart(), onPause(), onStop() etc.. methods
EditText x;
x.addTextChangedListener(new XyzTextWatcher());
XyzTextWatcher implements TextWatcher() {
public synchronized void afterTextChanged(Editable text) {
String s = formatText(text);
MyClass.this.x.setText(s);
}
}
}
為了防止速度變慢,為什么不改變 formatText 方法呢?
To prevent the slowdown why not change the formatText method something like this?
private Editable formatText(Editable text) {
int sep1Loc = 3;
int sep2Loc = 7;
if(text.length==sep1Loc)
text.append('-');
if(text.length==sep2Loc)
text.append('-');
return text;
}
注意:我沒有測試過這個
這篇關于在 TextWatcher 中更改文本后 EditText 未更新的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!