1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
| package com.tangyin.mobile.newsyun.utils;
import android.text.InputFilter.LengthFilter; import android.text.Spanned;
public class CustomLengthFilter extends LengthFilter { private int max; private onFullListener listener;
public CustomLengthFilter(final int max) { super(max); this.max = max; } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { int mlength = getLength(dest.subSequence(dstart, dend).toString()); int dlength = getLength(dest.toString()); int slength = getLength(source.subSequence(start, end).toString()); int keep = this.max - (dlength - mlength); if (keep <= 0) { if (null != listener) { listener.isFull(); } return ""; } else if (keep >= slength) { return null; } else { int tmp = 0; int index; for (index = start; index <= end; index++) { if (isFullwidthCharacter(source.charAt(index))) { tmp += 2; } else { tmp += 1; } if (tmp > keep) { break; } } if (null != listener) { listener.isFull(); } return source.subSequence(start, index); } } public void setOnFullListener(onFullListener listener) { this.listener = listener; } public interface onFullListener {
void isFull(); }
public static boolean isNull(final String str) { if (null == str || "".equals(str)) { return true; } else { return false; } }
public static int getLength(final String str) { if (isNull(str)) { return 0; } int len = str.length(); for (int i = 0; i < str.length(); i++) { if (isFullwidthCharacter(str.charAt(i))) { len = len + 1; } } return len; }
public static int getFwCharNum(final String str) { if (isNull(str)) { return 0; } int num = 0; for (int i = 0; i < str.length(); i++) { if (isFullwidthCharacter(str.charAt(i))) { num++; } } return num; }
public static boolean isFullwidthCharacter(final char ch) { if (ch >= 32 && ch <= 127) { return false; } else if (ch >= 65377 && ch <= 65439) { return false; } else { return true; } } }
|