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();
}