以前用過android.text.TextWatcher來監聽文本發生變化,但沒有仔細去想它,今天興致來了就發個瘋來玩玩吧!
有點擔心自己理解錯,所以還是先把英文API解釋給大家看看
1、什么情況下使用了?
When an object of a type is attached to an Editable, its methods will be called when the text is changed.
2、下面是它的三個抽象方法
?
/**
*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. It is an error to attempt to make changes to s from this callback.
*/
public 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 have just replaced old text that had length *before. It is an error to attempt to make changes to s from this callback.
*/
public void onTextChanged(CharSequence s, int start, int before, int count)/**
*This method is called to notify you that, somewhere within s, the text has been changed. It is legitimate(合理) to make further changes to s *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 Spannable.setSpan in onTextChanged to mark your place *and then look up from here where the span ended up.
*/
public void afterTextChanged(Editable s)
3、英文看的不汪不楚的,還是實際來進行調試看結果(注意我是按他們觸發的順序來進行排列的)
?
?
我輸入結果:a ab about abou
得到的結果:
s:是改變前的結果,start是改變前的位置,count是減少時改變的個數,after是增加時改變的個數
beforeTextChanged(CharSequence s, int start, int count,int after) //null 0 0 1//a 1 0 1//ab 2 0 3//about 4 1 0
s:是改變后的結果,start是改變前的位置,before是減少時改變的個數,count是增加時改變的個數
onTextChanged(CharSequence s, int start, int before,int count)//a 0 0 1//ab 1 0 1//about 2 0 3//abou 4 1 0afterTextChanged(Editable s)//a//ab//about//abou
現在來看看怎么實現吧
?
首先是實現他的接口?implements?TextWatcher
這是他的監聽事件addTextChangedListener(this)