对于一些需求,如非法字符限制(例如不允许输入#号,如果输入了#给出错误提示),做成动态判断更方便一些,而且容易扩展;

在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{       /**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.        * 在s中,从start处开始的count个字符将要被长度为after的文本替代        * s 为变化前的内容;        * start 为开始变化位置的索引,从0开始计数;        * count 为将要发生变化的字符数        * after 为用来替换旧文本的长度,比如s由1变为12,after为1,由12变为1,after为0;        */@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {// TODO Auto-generated method stubLog.i("test1", "before:s,"+s+",start,"+start+",count,"+count+",after,"+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        *  在s中,从start处开始的count个字符刚刚替换了原来长度为before的文本        *  s 为变化后的内容;        *  start 为开始变化位置的索引,从0开始计数;        *  before 为被取代的老文本的长度,比如s由1变为12,before为0,由12变为1,before为1;        *  count 为将要发生变化的字符数        */@Overridepublic void onTextChanged(CharSequence s, int start, int before,int count) {// TODO Auto-generated method stubLog.i("test1", "ing:s,"+s+",start,"+start+",before,"+before+",count,"+count);}       /**        * This method is called to notify you that, somewhere within s, the text has been changed.        */@Overridepublic void afterTextChanged(Editable s) {// TODO Auto-generated method stubLog.i("test1", "after,s,"+s);}}


注册监听:

EditText mEditor = (EditText)findViewById(R.id.editor_input);mEditor.addTextChangedListener(mTextWatcher);

更多相关文章

  1. Android(安卓)使用SpannableString显示复合文本
  2. Android探索:全面分析Activity的生命周期&IntentFilter匹配规则
  3. Android监测手机网络状态变化的广播
  4. Android积累之《Android(安卓)strings.xml文件定义字符串中的标
  5. android jni 实现
  6. android_5 修改一个textview中的字符串的颜色
  7. Android(安卓)滚动字幕实现
  8. Android(安卓)studio 高级控件提示文本框与下拉框
  9. android下libgdx 中文字符显示初探

随机推荐

  1. Android(安卓)使用USB进行数据传输
  2. Android(安卓)Rect类的构造函数参数说明
  3. Android(安卓)Fragment实践(二)
  4. Ubuntu 下用 Eclipse 编译调试 Android(
  5. Android原生GPS和网络定位工具类
  6. Android下 SQLite的使用
  7. Windows X64下安装SDK Platform
  8. android 控件layout的显示和消失 visibil
  9. Android一些知识点汇总
  10. 【Android(安卓)UI】具有弹性的ListView