text控件限制长度

public static class AmiLengthInputFilter extends InputFilter.LengthFilter{
	    private Context context;
		private Toast mToast;
		public AmiLengthInputFilter(int length, Context context) {
			
			super(length);
			Log.e("AmiLengthInputFilter", "AmiLengthInputFilter contrucstor begin");
			this.context = context;
			// TODO Auto-generated constructor stub
		}

		@Override
		public CharSequence filter(CharSequence source, int start, int end,
				Spanned dest, int dstart, int dend) {
			// TODO Auto-generated method stub
			Log.e("AmiLengthInputFilter", "super.filter begin");
			CharSequence charSequence = super.filter(source, start, end, dest, dstart, dend);
			Log.e("AmiLengthInputFilter", "super.filter end");
			if(charSequence != null){
				Log.e("AmiLengthInputFilter", "charSequence.equals(\"\")");
			   if(null == mToast){
				   mToast = Toast.makeText(context, R.string.limit_length, Toast.LENGTH_SHORT);
				   mToast.show();
			   }else{
				   Log.e("AmiLengthInputFilter", "mToast not null");
				   mToast.cancel();
				   mToast = Toast.makeText(context, R.string.limit_length, Toast.LENGTH_SHORT);
				   mToast.show();
			   }	
			}
			return charSequence;
		}
	}

下面是LengthInputFilter的源码

 

InputFilter方法filter 解释

按backspace键时,不会马上删除输入框中的内容,而先删掉之前输入但没显示出来的东西。

//测试结果是,在没满的时候返回null。在满的时候(达到maxlength),点得快的时候是返回“”,点得慢是返回整个字符串。

public static class LengthFilter implements InputFilter {
        private final int mMax;

        public LengthFilter(int max) {
            mMax = max;
        }

        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                int dstart, int dend) {//source是新增字符串所在charsequence,start和end是是新增字符的index范围,可知source还存有其他东西,而不只是
                                       //本次新增的东西
            int keep = mMax - (dest.length() - (dend - dstart));//dend和dstart应该是冗余长度,

//(dest.length() - (dend - dstart))是实际长度,keep则是表示还剩下的空间。

 if (keep <= 0) {//表示已达到上限 return ""; 
} else if (keep >= end - start) {//空间可容纳全部新增的字符 return null; // keep original 
} else {//有空间但是不够容纳所有字符 keep += start;
 if (Character.isHighSurrogate(source.charAt(keep - 1))) { --keep; if (keep == start) { return ""; } }
 return source.subSequence(start, keep); } } 

/** * @return the maximum length enforced by this input filter */ 
public int getMax() { return mMax; } }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值