android edittext 限制小數點后最多只能輸入兩位數字


 

    android:inputType="numberDecimal"

 

private InputFilter lengthFilter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// source:當前輸入的字符
// start:輸入字符的開始位置
// end:輸入字符的結束位置
// dest:當前已顯示的內容
// dstart:當前光標開始位置
// dent:當前光標結束位置
LogUtil.i("", "source=" + source + ",start=" + start + ",end=" + end + ",dest=" + dest.toString() + ",dstart=" + dstart + ",dend=" + dend);
if (dest.length() == 0 && source.equals(".")) {
return "0.";
}
String dValue = dest.toString();
String[] splitArray = dValue.split("\\.");
if (splitArray.length > 1) {
String dotValue = splitArray[1];
if (dotValue.length() == 2) {//輸入框小數的位數
return "";
}
}
return null;
}
};

edit.setFilters(new InputFilter[]{lengthFilter});




class   MyInputFilter implements InputFilter{
public MyInputFilter(int dotLength) {
this.dotLength = dotLength;
}

int dotLength ;

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
// source:當前輸入的字符
// start:輸入字符的開始位置
// end:輸入字符的結束位置
// dest:當前已顯示的內容
// dstart:當前光標開始位置
// dent:當前光標結束位置
LogUtil.i("", "source=" + source + ",start=" + start + ",end=" + end + ",dest=" + dest.toString() + ",dstart=" + dstart + ",dend=" + dend);
if (dest.length() == 0 && source.equals(".")) {
return "0.";
}
String dValue = dest.toString();
String[] splitArray = dValue.split("\\.");
if (splitArray.length > 1) {
String dotValue = splitArray[1];
if (dotValue.length() == dotLength) {//輸入框小數的位數
return "";
}
}
return null;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM