edittext实现只能输入数字,且最多保留两位小数

2018-09-28  本文已影响0人  王大碗要努力
1、xml布局
<EditText
                        android:id="@+id/edHotTempValue"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:background="@drawable/edit_bg"
                        android:paddingLeft="10dp"
                        android:inputType="number|numberDecimal"
                        android:text="0" />
2、edittext监听

private int selectionStart;
private int selectionEnd;
edittext.addTextChangedListener(new TextWatcher() {
            @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) {
                selectionStart = edittext.getSelectionStart();
                selectionEnd = edittext.getSelectionEnd();
                if(!edHotTempValue.getText().toString().equals("")){
                if (!isOnlyPointNumber(edittext.getText().toString())){
                    ToastUtils.showLong("您输入的数字保留在小数点后两位");
                    //删除多余输入的字(不会显示出来)
                    s.delete(selectionStart - 1, selectionEnd);
                    edittext.setText(s);
                }
                }
            }
        });

public static boolean isOnlyPointNumber(String number) {//保留两位小数正则
        Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,1}$");
        Matcher matcher = pattern.matcher(number);
        return matcher.matches();
    }


上一篇下一篇

猜你喜欢

热点阅读