遇到一需求,要限制EditText小数点输入位数,最后经过查阅资料,实现方法如下:

①xml中限制输入的类型:

android:inputType="numberDecimal"

②重写InputFilter

public class DecimalDigitsInputFilter implements InputFilter {    private final int decimalDigits;    /**     * Constructor.     *     * @param decimalDigits maximum decimal digits     */    public DecimalDigitsInputFilter(int decimalDigits) {        this.decimalDigits = decimalDigits;    }    @Override    public CharSequence filter(CharSequence source,                               int start,                               int end,                               Spanned dest,                               int dstart,                               int dend) {        int dotPos = -1;        int len = dest.length();        for (int i = 0; i < len; i++) {            char c = dest.charAt(i);            if (c == '.' || c == ',') {                dotPos = i;                break;            }        }        if (dotPos >= 0) {            // protects against many dots            if (source.equals(".") || source.equals(","))            {                return "";            }            // if the text is entered before the dot            if (dend <= dotPos) {                return null;            }            if (len - dotPos > decimalDigits) {                return "";            }        }        return null;    }}

③设置小数点位数,这里传进去的是2位

etInvoiceAmount.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(2)});

更多相关文章

  1. 重写Button实现图片drawableTop和文字一起居中
  2. Android重写onConfigurationChanged规避横竖屏切换时候重新进入o
  3. android edittext 限制输入框小数位数
  4. Android 中可重写的一些样式
  5. fullScreen时的软键盘监听(非重写Layout方式)
  6. android重写Dialog(接上文)
  7. 重写dialog
  8. 13、Android重写系统返回键
  9. Android -- 重写android返回键

随机推荐

  1. Android中使用Java代码动画改变背景颜色
  2. android窗体加载过程剖析之消息处理的注
  3. android代码执行adb shell终端命令(linux
  4. Android(安卓)一个简易的自定义软键盘
  5. 让JNI告诉你 你的应用为什么被卸载
  6. 用.Net打造一个移动客户端(Android/IOS)的
  7. Android沉浸式状态栏完全解析
  8. 把Android源代码加入SDK,就可以按F3查看类
  9. android单元测试中的多线程以及handler消
  10. 彻底掌握Android多分包技术MultiDex-用An