最近做一个非常简单的功能是用EditText输入价格,需求是第一位不能输入小数点,并且要保留小数点后两位。
起初上网百度了一个方法,但是不够严谨,会crash,所以我在这里把他的方法优化了一下。
1.首先,要输入浮点型数字,在xml的EditText里要加上一个属性:android:inputType="numberDecimal";
2.然后在该EditText所在的Activity或者Fragment里加上:(此功能是设置edit允许输入数字并且可以是小数;)
yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_VARIATION_NORMAL);
3.最后添加输入监听:
yourEditText.addTextChangedListener(new TextWatcher() {
private int selectionStart;
private int selectionEnd;
@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 = yourEditText.getSelectionStart();
selectionEnd = yourEditText.getSelectionEnd();
if (!isOnlyPointNumber(askPriceEdt.getText().toString()) && s.length() > 0) {
//删除多余输入的字(不会显示出来)
s.delete(selectionStart - 1, selectionEnd);
yourEditText.setText(s);
yourEditText.setSelection(s.length());
}
}
});
/**
* 保留两位小数正则
*
* @param number
* @return
*/
public static boolean isOnlyPointNumber(String number) {
Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,2}$");
Matcher matcher = pattern.matcher(number);
return matcher.matches();
}