对于一些需求,如非法字符限制(例如不允许输入#号,如果输入了#给出错误提示),做成动态判断更方便一些,而且容易扩展;
在Android里使用TextWatcher接口可以很方便的对EditText进行监听;TextWatcher中有3个函数需要重载:
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可以给出变化之前的内容,onTextChanged和afterTextChanged给出追加上新的字符之后的文本;
- class MyWatcher implements TextWatcher{
-
-
-
-
-
-
-
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count,
- int after) {
-
- Log.i("test1", "before:s,"+s+",start,"+start+",count,"+count+",after,"+after);
-
- }
-
-
-
-
-
-
-
-
-
- @Override
- public void onTextChanged(CharSequence s, int start, int before,
- int count) {
-
- Log.i("test1", "ing:s,"+s+",start,"+start+",before,"+before+",count,"+count);
-
- }
-
-
-
- @Override
- public void afterTextChanged(Editable s) {
-
- Log.i("test1", "after,s,"+s);
-
- }
- }
注册监听:
EditText mEditor = (EditText)findViewById(R.id.editor_input);
mEditor.addTextChangedListener(mTextWatcher);