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之间的数 并且输入错误能自动删除
时间: 2024-12-30 03:52:50