有些时候需要用到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 | after / before | |
beforeTextChanged | s = | 0 | 0 | a = 3 |
onTextChanged | s = cmd | 0 | 3 | b = 0 |
afterTextChanged | s = cmd | |
|
|
结合上面的Javadoc 来看:
beforeTextChanged:the count
characters beginning atstart
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.
也就是说:从start(=0) 位置开始,有count(=0)个字符将被替换为长度为after(=3)的新文字。
解释:
onTextChanged -- Javadoc:
This method is called to notify you that, within s
, the count
characters beginning atstart
have just replaced old text that had length before
. It is an error to attempt to make changes to s
from this callback.
解释:
cmd | |||
s | start | count | after / before |
s = cmd | 0 | 2 | a = 0 |
s = d | 0 | 0 | b = 2 |
s = d | |
|
|
// 试验2:
// 前提条件: EditText 中已经有 abcd 这4个字符
// Part 1: 选中 abc, 并删除
// Part 2: 粘贴 abc
// Part 3: 在 c 和 d 之间粘贴 1234 这4个字符
// Part 1: 选中 abc, 并删除
Test 3 | |
|
|
|
ab1cd -- > axd | ||||
s | start | count | after / before | |
beforeTextChanged | s = ab1cd | 1 | 3 | a = 1 |
onTextChanged | s = axd | 1 | 1 | b = 3 |
afterTextChanged | s = axd | |
|
|