onTextChanged vs Android中的afterTextChanged - 需要实时示例

Sim*_*Guy 14 android android-textwatcher

我正在阅读Android编程中的TextWatcher.我无法理解afterTextChanged和onTextChanged之间区别.

虽然我提到了 TextWatcher的onTextChanged,beforeTextChanged和afterTextChanged之间的差异,但是当我需要使用onTextChanged而不是afterTextChanged时,我仍然无法想到这种情况.

Sim*_*Guy 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.
Run Code Online (Sandbox Code Playgroud)

所以,两者之间的区别是:

  • 我可以改变我的文字afterTextChanged,onTextChanged但不允许我这样做
  • onTextChanged给出了改变位置的偏移量,而afterTextChanged没有


Ann*_*arg 6

只是在 Pratik Dasa 的回答以及评论中与 @SimpleGuy 的讨论中添加一些内容,因为我没有足够的声誉来发表评论。

这三个方法也是由 触发的EditText.setText("your string here")。这将使长度为 16(在本例中),因此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)
Run Code Online (Sandbox Code Playgroud)

afterTextChanged这就是和之间的区别onTextChanged:参数。

另请查看此线程中接受的答案:Android TextWatcher.afterTextChanged vs TextWatcher.onTextChanged

  • 另外,当将一些文本粘贴到 EditText 时,“count”不会是 1。 (2认同)