Android 控制edittext或者textview输入的为指定的整数位和小数位

Android 控制edittext或者textview输入的为指定的整数位和小数位,关于这个博客有一篇文章,不过要补充的是自定义键盘上如果出现00,或者其他自定义的数据如20000之类的,对于控制小数位的方式,代码如下:

package client.verbank.mtp.allone.component.util;

import android.text.InputFilter;
import android.text.Spanned;

public class ComponentDigitCtrlFilter implements InputFilter {

	private boolean isJPY;
	private int digit;

	public ComponentDigitCtrlFilter(boolean isJPY, int digit) {
		this.isJPY = isJPY;
		this.digit = digit;
	}

	@Override
	public CharSequence filter(CharSequence source, int start, int end,
			Spanned dest, int dstart, int dend) {
		// 删除等特殊字符,直接返回
		if ("".equals(source.toString())) {
			return null;
		}
		String oriValue = dest.toString();
		StringBuffer sb = new StringBuffer(oriValue);
		sb.append(source);
		String newValue = sb.toString();
		String[] newValueVec = newValue.split("\\.");
		System.out.println("test11111111111 " + newValueVec[0]);
		if (newValueVec.length == 2) {
			double number = Double.parseDouble(newValueVec[0]);
			boolean numberflag = true;
			if (isJPY) {
				numberflag = ((number - 999 > 0.000001) ? false : true);
			} else {
				numberflag = ((number - 99 > 0.000001) ? false : true);
			}

			boolean digitflag = true;
			try {
				String digitNumber = newValueVec[1];
				digitflag = digitNumber.toCharArray().length > digit ? false
						: true;
			} catch (Exception ex) {
				digitflag = false;
			}
			if (numberflag && digitflag) {
				return source;
			} else {
				return "";
			}
		} else {
			double value = Double.parseDouble(newValue);
			if (isJPY) {
				return value > 999 ? "" : source;
			} else {
				return value > 99 ? "" : source;
			}
		}
		// dest.subSequence(dstart, dend)
	}
}


你可能感兴趣的:(android,filter,textview)