Android 限制edittext 整数和小数位数 过滤器

    写了一个过滤器,根据需要限制edittext输入的整数和小数位,如下代码:

package allone.verbank.apad.client.component;

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

/**
 * 
 * @Title: ComponentDigitCtrlFilter.java 
 * @Package allone.verbank.apad.client.component 
 * @Description: 为了限制edit根据商品输入指定的位数和小数位
 * @author qiulinhe qiu.linhe@allone.cn 
 * @date 2016年3月21日 上午10:49:30   
 */
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("\\.");
		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)
	}
}
逻辑是判断传入的isJPY是否是要整数两位小数三位数的,然后对输入的数据进行限制,只需要将过滤器添加到对应的edittext控件即可,如下:stopEditText.setFilters(new InputFilter[] { new ComponentDigitCtrlFilter(digit == 2, digit) });

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值