onTextChanged vs afterTextChanged in Android - 需要实时示例



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

虽然我提到TextWatcher 的 onTextChanged、beforeTextChanged 和 After TextChanged 之间的差异,我仍然想不出我需要使用 onTextChanged() 而不是 afterTextChanged() 的情况。

我在 Android 开发者门户上找到了对此的解释

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不允许我这样做
  • onTextChanged 给了我更改的位置的偏移量,而 afterTextChanged 则没有

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

这就是afterTextChangedonTextChanged之间的区别所在:参数。

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

以下是

解释:

onTextChanged :这意味着当你开始打字时,就像你想写"sports"一样,这将调用每个字符,就像当你按下"s"然后再次按下"p"然后"o"依此类推时它会调用......

afterTextChanged :这会在您停止打字时调用,它会在您完全写"运动"后调用,这是主要区别。

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
                        }
                    }
                });

相关内容

  • 没有找到相关文章

最新更新