Android 限制EditText只能輸入數字、限制輸入型別、限制輸入長度的小技巧
阿新 • • 發佈:2019-02-07
準確的說讓Edittext只能輸入數字有方法兩種,都是通過xml屬性設定
方法一:
- <EditText
- android:id="@+id/u_account"
- android:layout_width="0dp"
- android:layout_height="match_parent"
- android:layout_marginLeft="13dp"
- android:inputType="phone|number"
-
android:maxLength
- android:numeric="integer" //這個屬性限制只能輸入數字
- android:singleLine="true"
- android:textColor="@color/hint_textcolor"
- android:textSize="14sp"/>
方法二:
- <EditText
- android:id="@+id/u_account"
- android:layout_width="0dp"
-
android:layout_height
- android:background="@drawable/signup_input_pw_text_bg"
- android:digits="1234567890" //這個屬性限制只能輸入0-9這些數字</span>
- android:inputType="phone|number"
- android:maxLength="11"
- android:singleLine="true"
-
android:textColor="@color/hint_textcolor"
- android:textSize="14sp"/>
雖然方法一二都可以,但方法一中 android:numeric="integer"已被官方放棄,所以不推薦使用。
使用方法而更好!與時俱進嘛!
上面是以前的部落格內容;
下面補充些常用的技巧,實現方式都分為兩種:
- 限制輸入型別
程式碼:et_lxnr.setInputType(InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE);
xml:android:inputType="number" - 限制輸入長度(如限制輸入最大長度10)
程式碼:et_lxnr.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
xml:android:maxLength="10" - 限制輸入固定的某些字元(如123456xyz)
程式碼:et_lxnr.setKeyListener(DigitsKeyListener.getInstance(“123456xyz”);
xml:android:digits="@string/input_num_character"