android之TextWatcher的监听

Posted 丨丿丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android之TextWatcher的监听相关的知识,希望对你有一定的参考价值。

以前用过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		0

afterTextChanged(Editable s)
	//a
	//ab
	//about
	//abou


现在来看看怎么实现吧

 

首先是实现他的接口 implements TextWatcher

这是他的监听事件addTextChangedListener(this)



以上是关于android之TextWatcher的监听的主要内容,如果未能解决你的问题,请参考以下文章

Android开发中给EditText控件添加TextWatcher监听实现对输入字数的限制

Android 软键盘监听回车之没辣么简单

Android使用TextWatcher匹配email造成ANR的解决

Android使用TextWatcher匹配email造成ANR的解决

Android使用TextWatcher匹配email造成ANR的解决

android 通过监听edittext实现button的点击事件