textwatcher 包含三个接口,分别对应文本框输入的三个状态,分别是输入前、输入中、输入完成。
1.改变前 beforeTextChanged
这个方法会在输入前调用,有四个参数分别是
CharSequence s: editview中原来的内容
int start : 本次替换的起始位置
int count: 本次替换内容的长度
int after: 新替换内容的长度
注释中说的很明白,这个方法被调用是用来通知你,原内容s从start位置开始的count个字符将为被长度为after的新内容替换,而不能在这个方法内改变s的内容。
/**
* This method is called to notify you that, within <code>s</code>,
* the <code>count</code> characters beginning at <code>start</code>
* are about to be replaced by new text with length <code>after</code>.
* It is an error to attempt to make changes to <code>s</code> from
* this callback.
*/
public void beforeTextChanged(CharSequence s, int start,
int count, int after);
2.改变中 onTextChanged
这个方法也有四个参数,和上一个方法不同的是把after换成来before,但别的参数的意思也有略微的改动。
CharSequence s: 代表替换后的内容。
int start:被替换的初始位置
int before:代表被替换内容的长度,对应上一个方法的count。
int count: 代表新内容的长度
这个方法是用来通知你,原本start位置后的before个字符已经被替换成count个新字符了。注意的是这个方法内同样不能对s进行改变
/**
* This method is called to notify you that, within <code>s</code>,
* the <code>count</code> characters beginning at <code>start</code>
* have just replaced old text that had length <code>before</code>.
* It is an error to attempt to make changes to <code>s</code> from
* this callback.
*/
public void onTextChanged(CharSequence s, int start, int before, int count);
3.改变后 afterTextChanged
这个方法只有一个参数。
Editable s 文本改变之后的内容
这个方法是用来通知你,之前s已经被修改了,在这个方法中你能够对s进行改动,但是需要注意的是别陷入死循环,因为每次改动都会再次调用这个方法进行递归。这个方法没有像之前的方法一样有多个参数来告诉你它改动的位置和长度,是因为与此同时可能有别的afterTextChanged也改动了,就会使得原来的信息告诉你也没用,因为很可能已经变化了。如果一定想要知道,可以在onTextChanged()中用setSpan()进行标志结束的位置。
需要的注意的是,此时虽然获取到了新内容,但是还没更新到UI上。
/**
* This method is called to notify you that, somewhere within
* <code>s</code>, the text has been changed.
* It is legitimate to make further changes to <code>s</code> 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 use {@link Spannable#setSpan} in {@link #onTextChanged}
* to mark your place and then look up from here where the span
* ended up.
*/
public void afterTextChanged(Editable s);
现在知道了这三个监听方法,我们就可以根据业务进行自定义化的操作了。