25

我正在阅读有关Android 编程中的TextWatcher的信息。我无法理解 和 之间的afterTextChanged()区别onTextChanged()

尽管我提到了 TextWatcher 的 onTextChanged、beforeTextChanged 和 afterTextChanged 之间的差异,但我仍然无法想到需要使用onTextChanged()而不是afterTextChanged().

4

3 回答 3

24

我在 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.

所以,两者的区别在于:

  • 我可以使用while不允许我这样做来更改我的文本afterTextChangedonTextChanged
  • onTextChanged 为我提供了更改位置的偏移量,而 afterTextChanged 没有
于 2014-11-18T12:39:39.447 回答
5

只需在 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)

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

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

于 2016-09-25T14:21:55.203 回答
-6

这是解释:

onTextChanged :这意味着当你开始输入时,就像你想写“sports”一样,这将调用每个字符,就像当你按下“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
                        }
                    }
                });
于 2014-11-18T10:53:10.310 回答