InputFilter EditText的过滤器

来源:互联网 发布:mac设置默认播放器 编辑:程序博客网 时间:2024/05/21 03:18

输入价格的过滤器,挺好找的。后来找不到了;

就自己写一个备份以后能用的到。


InputFilter 只能限制输入的内容,并不能更改其内容


代码简单就不多说废话了。希望你能用的到

import android.text.InputFilter;import android.text.Spanned;/** * 用于过滤 输入价格 * Created by mrqiu on 2017/7/17. */public class NumberFilter implements InputFilter {    //用于关闭小数点后的限制    public static final int CLOSE_DECIMAL_LENGTH = -1;    private int decimalLength = 2;    private static final String SYMBOL = ".";    private static String[] KEY_INPUT_NUMBER = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "."};    @Override    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {        /*         CharSequence source,  //当前输入的内容,          int start,  //开始位置          int end,  //结束位置          Spanned dest, //当前显示的内容          int dstart,  //当前开始位置          int dend //当前结束位置         */        String nowInputChar = source.toString();        //用于过滤当前输入的字符是否为空;        if (nowInputChar.isEmpty()) {            return source.subSequence(start, end);        }        boolean isNumber = false;        for (int i = 0; i < KEY_INPUT_NUMBER.length; i++) {            if (KEY_INPUT_NUMBER[i].equals(nowInputChar)) {                isNumber = true;                break;            }        }        if (!isNumber) {            return "";        }        String content = dest.toString();        if (content.contains(SYMBOL)) {            if (SYMBOL.equals(nowInputChar)) {                return "";            }            if (CLOSE_DECIMAL_LENGTH != decimalLength) {                String[] str = content.split("\\.");                if (str.length > 1) {                    //用于拦截小数点位数;                    String floatNub = str[1];                    if (floatNub.length() >= decimalLength) {                        return "";                    }                }            }        } else {            /*            *  判断用户首次输入 '0' 或者 ,'.' 自动生成 '0.'            */            if (content.length() == 0 && (nowInputChar.equals(SYMBOL) || nowInputChar.equals("0"))) {                return "0.";            }        }        return source.subSequence(start, end);    }    /**     * 用于设置小数点长度     * @param len     */    public void setDecimalLength(int len) {        decimalLength = len;    }}

在去设置EdiText 的过滤器

NumberFilter nf = new NumberFilter();et.setFilters(new InputFilter[]{nf});


需要设置小数点后面的长度,可以通过setDecimalLength  进行设置;

如果需要关闭限制,可以通过 setDecimalLength  传入CLOSE_DECIMAL_LENGTH 的常量进行设置;









原创粉丝点击