最近做一個非常簡單的功能是用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());
}
}
});
public static boolean isOnlyPointNumber(String number) {
Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,2}$");
Matcher matcher = pattern.matcher(number);
return matcher.matches();
}