Android EditText输入最大值提示功能

public class LengthFilter implements InputFilter {  
     public LengthFilter(int max) {  
         mMax = max;  
     }  
  
     @Override  
     public CharSequence filter(CharSequence source, int start, int end,  
             Spanned dest, int dstart, int dend) {  
         int keep = mMax - (dest.length() - (dend - dstart));  
  
         if (keep <= 0) {  
             if (mErrorToast == null) {  
                 mErrorToast = Toast.makeText(ShowDetailCommentActivity.this, R.string.comment_input_overflow,  
                         Toast.LENGTH_SHORT);  
             }  
             mErrorToast.show();  
             return "";  
         } else if (keep >= end - start) {  
             return null; // keep original  
         } else {  
             keep += start;  
             if (mErrorToast == null) {  
                 mErrorToast = Toast.makeText(ShowDetailCommentActivity.this, R.string.comment_input_overflow,  
                         Toast.LENGTH_SHORT);  
             }  
             mErrorToast.show();  
             if (Character.isHighSurrogate(source.charAt(keep - 1))) {  
                 --keep;  
                 if (keep == start) {  
                     return "";  
                 }  
             }  
             return source.subSequence(start, keep);  
         }  
     }  
  
     private int mMax;  
 }  
mEditText.setFilters(new InputFilter[] { new LengthFilter(mMaxTextNum) });  

代码很少但有效,各位可以尝试一下。

 

作者:xzy2046,转载需注明。博客主页:http://blog.csdn.net/xzy2046
posted @ 2015-07-13 16:57  developer_Kale  阅读(1539)  评论(2编辑  收藏
网站流量统计工具