本文介绍Andrid中监听TextView、EditText文本变化的方法。
点击查看"TextView示例源码"。
1. 自定义定义文本监听类
private class MyTextWatcher implements TextWatcher {
// cs中从start开始的count个字符即将被after个字符替换
@Override
public void beforeTextChanged(CharSequence cs, int start, int count, int after) {
}
// cs中从start开始的before个字符刚刚被count个字符替换
@Override
public void onTextChanged(CharSequence cs, int start, int before, int count) {
Log.d(TAG, "onTextChanged, cs="+cs+", start="+start+", before="+before+", count="+count);
}
@Override
public void afterTextChanged(Editable arg0) {
}
}
2. 设置监听
mTextView = (TextView) findViewById(R.id.tv);
mTextView.addTextChangedListener(new MyTextWatcher());