1. 程式人生 > >Edittext判斷輸入是否為數字(包含小數點)

Edittext判斷輸入是否為數字(包含小數點)

在開發中EditText總會要求輸入限制,數字?個數?幾行?

1.在限制輸入型別為double的數字時就需要做兩步判斷,

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numeric="decimal" />

在佈局中定義EditText的時候設定為只能輸入數字,設定數字的時候可以直接設定android:numeric="decimal" ;

然後再進行具體判斷

/**
 * 判斷字串是否是數字
*/
public static boolean isNumber(String value) {
    return 
isInteger(value) || isDouble(value); } /** * 判斷字串是否是整數 */ public static boolean isInteger(String value) { try { Integer.parseInt(value); return true; } catch (NumberFormatException e) { return false; } } /** * 判斷字串是否是浮點數 */ public static boolean isDouble(String value) { try
{ Double.parseDouble(value); if (value.contains(".")) return true; return false; } catch (NumberFormatException e) { return false; } }

2.限制輸入小數位數

需要給EditText設定TextWatcher,在輸入的時候進行判斷

TextWatcher mTextWatcher = new TextWatcher() {

    @Override
public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { String temp = s.toString(); int posDot = temp.indexOf("."); if (posDot <= 0) return; if (temp.length() - posDot - 1 > 4) { s.delete(posDot + 5, posDot + 6); } } };


希望能幫助到小夥伴們……