/** * 以Byte数的方式来实现的LengthFilter * @author bvin */ public class OneByteInputFilter implements InputFilter{ private final int mMax; public OneByteInputFilter(int mMax) { super(); this.mMax = mMax; } @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { //int remainLength = dest.length()-(dend-dstart); CharSequence placeStart = dest.subSequence(0, dstart); CharSequence placeEnd = dest.subSequence(dend, dest.length()); int placeStartLength = Util.computeLenthByByte(placeStart.toString()); int placeEndLength = Util.computeLenthByByte(placeEnd.toString()); int canReplaceSize = mMax-placeStartLength-placeEndLength; if (canReplaceSize>0) { CharSequence sourceSpan = source.subSequence(start, end); int sourceSpanLength = Util.computeLenthByByte(sourceSpan.toString()); if (sourceSpanLength>=canReplaceSize) {//替换内容长度大于可容纳长度 String result = fixSplit(sourceSpan.toString(), canReplaceSize, false); if (!TextUtils.isEmpty(result)) { return result; }else { return ""; } }else { return null; } }else { return ""; } } private static String fixSplit(String s,int sum,boolean debug){ int counter = 0; String fixString = null; for (int i = 0; i < s.length(); i++) { if (counter>=sum) { break; } int length = (s.charAt(i)+"").getBytes().length; if(length>1){ counter += 2; if (counter<=sum) { fixString = s.substring(0, i+1); } } else if (length==1){ if (counter<=sum) { fixString = s.substring(0, i+1); } ++counter; }else {//小于1 continue; } /*if (counter>=sum) { System.out.println("break;"+counter); break; }else { fixString = s.substring(0, i+1); }*/ } return fixString; } }
时间: 2024-10-28 15:48:03