码迷,mamicode.com
首页 > 其他好文 > 详细

通过正则表达式的进行输入限制的TextWatcher

时间:2016-07-21 19:37:55      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

1 通过handler来修改edittext 的只 

public static class MileTextWatcher implements TextWatcher {
        public EditText editText;
        public Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (MILE_DISABLE) {
                    case MILE_DISABLE:
                        String args = (String) msg.obj;
                        editText.setText(args.substring(0, args.length() - 1));
                        editText.setSelection(args.length() - 1);
                        break;
                }
            }
        };
        ;

        public MileTextWatcher(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(s.toString()) || s.toString().equals("0")) {
                return;
            }
            if (s.charAt(0) == ‘.‘) {
                editText.setText("0.");
                editText.setSelection(2);
                return;
            }
            String reg = "^([1][0]{0,2}?)|^([1-9][0]{0,1}?)|^([1-9]{1,2}?)";
            if (!s.toString().contains(".") && !Pattern.compile(reg).matcher(s.toString()).matches()) {
                handler.obtainMessage(MILE_DISABLE, s.toString()).sendToTarget();
            }
            String reg2 = "^([0][.][0-9]{0,2}?)|^([1-9][0-9]{0,1}?)+([.][0-9]{0,2}?)";
            if (s.toString().contains(".") && !Pattern.compile(reg2).matcher(s.toString()).matches()) {
                handler.obtainMessage(MILE_DISABLE, s.toString()).sendToTarget();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

2 这个能实现输入0-99.99之间的数 并且输入错误能自动删除

通过正则表达式的进行输入限制的TextWatcher

标签:

原文地址:http://www.cnblogs.com/seanzhoutao/p/5692733.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!