TextWatcher

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

     在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;
        */
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			Log.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 为将要发生变化的字符数
        */
		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			Log.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.
        */
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			Log.i("test1", "after,s,"+s);
			
		}
}


     注册监听:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值