美文网首页
NumTextWatcher Edittext 监听输入的小数位

NumTextWatcher Edittext 监听输入的小数位

作者: 一劍 | 来源:发表于2018-10-25 10:00 被阅读0次

    主要是针对 需要限制小数位数的输入框做的监听处理

    public class NumTextWatcher implements TextWatcher {
    private int defaultRetain = 2;
    private EditText edit;
    
    public NumTextWatcher(@NonNull EditText edit, int retainDecimal, AfterTextChange chang) {
        this.defaultRetain = retainDecimal;
        this.edit = edit;
        this.mChange = chang;
    }
     @Override
      public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
    }
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    
    }
    
    @Override
    public void afterTextChanged(Editable s) {
        CharSequence afterChange = s.toString();
        if (TextUtils.isEmpty(afterChange)) {
            if (mChange != null)
                mChange.afterText(afterChange);
            return;
        }
        //删除“.”后面超过2位后的数据
        if (afterChange.toString().contains(".")) {
            int first = afterChange.toString().indexOf(".");
            int last = afterChange.toString().lastIndexOf(".");
            if (first == last) {
                if (afterChange.length() - 1 - first > defaultRetain) {
                    afterChange=afterChange.subSequence(0, first + defaultRetain + 1);
                    this.edit.setText(afterChange);
                    this.edit.setSelection(afterChange.length()); //光标移到最后
                }
            } else {
                afterChange=afterChange.subSequence(0, last);
                this.edit.setText(afterChange.subSequence(0, last));
                this.edit.setSelection(afterChange.length()); //光标移到最后
            }
    
        }
        //如果"."在起始位置,则起始位置自动补0
        if (afterChange.toString().trim().substring(0).equals(".")) {
            afterChange = "0" + afterChange;
            this.edit.setText(afterChange);
            this.edit.setSelection(2); //光标移到最后
        }
        //如果起始位置为0,且第二位跟的不是".",则无法后续输入
        if (afterChange.toString().startsWith("0") && afterChange.toString().trim().length() > 1) {
            if (!afterChange.toString().substring(1, 2).equals(".")) {
                this.edit.setText(afterChange.subSequence(0, 1));
                this.edit.setSelection(1);
                return;
            }
        }
    
        if (mChange != null)
            mChange.afterText(afterChange);
    }
    
    private AfterTextChange mChange;
    
     public interface AfterTextChange {
        void afterText(CharSequence after);
    }
    }

    相关文章

      网友评论

          本文标题:NumTextWatcher Edittext 监听输入的小数位

          本文链接:https://www.haomeiwen.com/subject/pxkqtqtx.html