首先提到一個輸入過濾器志群,用來約束用戶輸入的內(nèi)容關(guān)鍵接口:InputFilters
我們現(xiàn)在要做的就是重寫這個接口
/**
* Created by jary on 2016/11/3.
* 設(shè)置小數(shù)位數(shù)控制
*/
public class PointLengthFilter implements InputFilter {
/** 輸入框小數(shù)的位數(shù) 示例保留一位小數(shù)*/
private static final int DECIMAL_DIGITS = 1;
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// 刪除等特殊字符,直接返回
if ("".equals(source.toString())) {
return null;
}
String dValue = dest.toString();
String[] splitArray = dValue.split("\\.");
if (splitArray.length > 1) {
String dotValue = splitArray[1];
int diff = dotValue.length() + 1 - DECIMAL_DIGITS;
if (diff > 0) {
return source.subSequence(start, end - diff);
}
}
return null;
}
}
調(diào)用示例
xml 代碼
<EditText
android:id="@+id/et_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal" //記得限制輸入類型為小數(shù)
/>
java代碼
etText= (EditText) findViewById(R.id.et_accounting_money);
etText.setFilters(new InputFilter[]{new Lengthfilter()});