在一些要輸入金額的輸入框中屯耸,通常會(huì)有限制輸入小數(shù)位數(shù)的要求拐迁,提供一個(gè)用TextWatcher實(shí)現(xiàn)的方式。
輸入規(guī)則:
1.輸入0時(shí)疗绣,不再進(jìn)行輸入
2.首位輸入小數(shù)點(diǎn)時(shí)线召,小數(shù)點(diǎn)前自動(dòng)補(bǔ)0
3.超出小數(shù)限制位數(shù),禁止繼續(xù)輸入
4.超出總限制字符數(shù)多矮,禁止輸入
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.widget.EditText;
/**
* Description: 小數(shù)位數(shù)限定
*/
public class DecimalInputTextWatcher implements TextWatcher {
private static final String Period = ".";
private static final String Zero = "0";
/**
* 需要設(shè)置該 DecimalInputTextWatcher 的 EditText
*/
private EditText editText = null;
/**
* 默認(rèn) 小數(shù)的位數(shù) 2 位
*/
private static final int DEFAULT_DECIMAL_DIGITS = 2;
private int decimalDigits;// 小數(shù)的位數(shù)
private int totalDigits;//最大長(zhǎng)度
/**
* @param editText editText
* @param totalDigits 最大長(zhǎng)度
* @param decimalDigits 小數(shù)的位數(shù)
*/
public DecimalInputTextWatcher(EditText editText, int totalDigits, int decimalDigits) {
if (editText == null) {
throw new RuntimeException("editText can not be null");
}
this.editText = editText;
if (totalDigits <= 0)
throw new RuntimeException("totalDigits must > 0");
if (decimalDigits <= 0)
throw new RuntimeException("decimalDigits must > 0");
this.totalDigits = totalDigits;
this.decimalDigits = decimalDigits;
}
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void afterTextChanged(Editable editable) {
try {
String s = editable.toString();
editText.removeTextChangedListener(this);
//限制最大長(zhǎng)度
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(totalDigits)});
if (s.contains(Period)) {
//超過(guò)小數(shù)位限定位數(shù),只保留限定小數(shù)位數(shù)
if (s.length() - 1 - s.indexOf(Period) > decimalDigits) {
s = s.substring(0,
s.indexOf(Period) + decimalDigits + 1);
editable.replace(0, editable.length(), s.trim());
}
}
//如果首位輸入"."自動(dòng)補(bǔ)0
if (s.trim().equals(Period)) {
s = Zero + s;
editable.replace(0, editable.length(), s.trim());
}
//首位輸入0時(shí),不再繼續(xù)輸入
if (s.startsWith(Zero)
&& s.trim().length() > 1) {
if (!s.substring(1, 2).equals(Period)) {
editable.replace(0, editable.length(), Zero);
}
}
editText.addTextChangedListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用時(shí):
edit需要先限定輸入方式:
示例.png
調(diào)用:
EditText numberDecimalEt = findViewById(R.id.number_decimal_et);
//輸入總長(zhǎng)度15位缓淹,小數(shù)2位
numberDecimalEt.addTextChangedListener(new DecimalInputTextWatcher(numberDecimalEt, 15, 2));