我正在阅读Android编程中的 TextWatcher 。我无法理解afterTextChanged和onTextChanged之间的区别。
虽然我提到过 Differences between TextWatcher 's onTextChanged, beforeTextChanged and afterTextChanged但是当我需要使用onTextChanged而不是afterTextChanged时,我仍然无法想到这种情况。
答案 0 :(得分:15)
我在Android Dev Portal上找到了对此的解释
http://developer.android.com/reference/android/text/TextWatcher.html
**abstract void afterTextChanged(Editable s)**
This method is called to notify you that, somewhere within s, the text has been changed.
**abstract void beforeTextChanged(CharSequence s, int start, int count, int after)**
This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after.
**abstract void onTextChanged(CharSequence s, int start, int before, int count)**
This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.
所以,两者之间的区别是:
afterTextChanged
更改我的文字,而onTextChanged
不允许我这样做答案 1 :(得分:1)
在评论中添加一些内容给Pratik Dasa的回答以及与@SimpleGuy的讨论,因为我没有足够的声誉来发表评论。
这三种方法也由else if
触发。这将使长度为16(在这种情况下),因此EditText.setText("your string here")
不总是count
。
请注意,三种方法的参数列表不同:
1
这就是abstract void afterTextChanged(Editable s)
abstract void beforeTextChanged(CharSequence s, int start, int count, int after)
abstract void onTextChanged(CharSequence s, int start, int before, int count)
和afterTextChanged
之间的差异:参数。
请同时查看此主题中接受的答案:Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged
答案 2 :(得分:-4)
这里有解释:
onTextChanged:这意味着当你开始打字时,就像你想写“体育”一样,这将调用每个角色,就像你按下“s”然后再按“p”然后“o”时调用等......
afterTextChanged:这会在你停止输入时调用,它会在你完全写下“sport”之后调用,这是主要的差异。
YOUR_EDIT_TEXT.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Your query to fetch Data
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
//Your query to fetch Data
}
}
});