EditText是Android中一個非常實用的控件,有很多InputType,可以來達到不同的輸入效果,如下圖:

比如,密碼輸入,數(shù)字輸入等等。但是最近在項目中要實現(xiàn)EditText輸入金額,金額的限制因素很多,比如,只能輸入數(shù)字和小數(shù)點,首位不能輸入0和小數(shù)點,小數(shù)點后面只能保留兩位等等,這些僅僅用InputType是無法實現(xiàn)的,今天用InputFilter來實現(xiàn)。
1. 首先需要將EditText的InputType設(shè)置成如下格式,保證用戶只能輸入小數(shù)點和數(shù)字
android:inputType="numberDecimal"或者setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL)
2. 自定義InputFilter,代碼如下:
CashierInputFilter.Java
package com.xylpay.utils; import android.text.InputFilter; import android.text.Spanned; import android.text.TextUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Jackie on 2016/1/30. * 過濾用戶輸入只能為金額格式 */ public class CashierInputFilter implements InputFilter { Pattern mPattern; //輸入的最大金額 private static final int MAX_VALUE = Integer.MAX_VALUE; //小數(shù)點后的位數(shù) private static final int POINTER_LENGTH = 2; private static final String POINTER = "."; private static final String ZERO = "0"; public CashierInputFilter() { mPattern = Pattern.compile("([0-9]|//.)*"); } /** * @param source 新輸入的字符串 * @param start 新輸入的字符串起始下標,一般為0 * @param end 新輸入的字符串終點下標,一般為source長度-1 * @param dest 輸入之前文本框內(nèi)容 * @param dstart 原內(nèi)容起始坐標,一般為0 * @param dend 原內(nèi)容終點坐標,一般為dest長度-1 * @return 輸入內(nèi)容 */ @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { String sourceText = source.toString(); String destText = dest.toString(); //驗證刪除等按鍵 if (TextUtils.isEmpty(sourceText)) { return ""; } Matcher matcher = mPattern.matcher(source); //已經(jīng)輸入小數(shù)點的情況下,只能輸入數(shù)字 if(destText.contains(POINTER)) { if (!matcher.matches()) { return ""; } else { if (POINTER.equals(source)) { //只能輸入一個小數(shù)點 return ""; } } //驗證小數(shù)點精度,保證小數(shù)點后只能輸入兩位 int index = destText.indexOf(POINTER); int length = dend - index; if (length > POINTER_LENGTH) { return dest.subSequence(dstart, dend); } } else { //沒有輸入小數(shù)點的情況下,只能輸入小數(shù)點和數(shù)字,但首位不能輸入小數(shù)點和0 if (!matcher.matches()) { return ""; } else { if ((POINTER.equals(source) || ZERO.equals(source)) && TextUtils.isEmpty(destText)) { return ""; } } } //驗證輸入金額的大小 double sumText = Double.parseDouble(destText + sourceText); if (sumText > MAX_VALUE) { return dest.subSequence(dstart, dend); } return dest.subSequence(dstart, dend) + sourceText; } }使用方法如下:

新聞熱點
疑難解答