欢迎来到代码驿站!

Android代码

当前位置:首页 > 移动开发 > Android代码

Android 限制edittext 整数和小数位数 过滤器(详解)

时间:2021-05-19 09:40:06|栏目:Android代码|点击:

写了一个过滤器,根据需要限制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 
 */
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) });

上一篇:Android使用Intent的Action和Data属性实现点击按钮跳转到拨打电话和发送短信界面

栏    目:Android代码

下一篇:Android中的设计模式

本文标题:Android 限制edittext 整数和小数位数 过滤器(详解)

本文地址:http://www.codeinn.net/misctech/124376.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有