有些时候需要用到TextWatcher来监听EditText的内容变化,
而TextWatcher有三个回调方法,
这三个回调方法在Android的API Document中说的并不是很容易理解,
我尝试用我的思路以及试验解释一下这三个回调方法的参数。
// **************************************************************
// 这一部分比较枯燥可以跳过,直接读试验部分
// 试验部分的结果会对比这一部分的Javadoc来确认对试验结果理解的正确性
三个回调方法分别是 (按回调的先后顺序):
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
public void afterTextChanged(Editable s) {}
beforeTextChanged -- Javadoc:
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 lengthafter
. It is an error to attempt to make changes tos
from this callback.
onTextChanged -- Javadoc:
This method is called to notify you that, within s
, the count
characters beginning at start
have just replaced old text that had lengthbefore
. It is an error to attempt to make changes tos
from this callback.
afterTextChanged -- Javadoc:
This method is called to notify you that, somewhere withins
, the text has been changed. It is legitimate to make further changes tos
from this callback, but be careful not to get yourself into an infinite loop, because any changes you make will cause this method to be called again recursively. (You are not told where the change took place because other afterTextChanged() methods may already have made other changes and invalidated the offsets. But if you need to know here, you can useSpannable.setSpan
inonTextChanged
to mark your place and then look up from here where the span ended up.
// **************************************************************
// 试验部分开始
// 试验1:
// Part 1: 粘贴 “cmd” 到EditText
// Part 2: 选中“cm”并删除
首先看 Part 1:
cmd | ||||
s | start | count |