1. 程式人生 > >Android 限制EditText只能輸入數字、限制輸入型別、限制輸入長度的小技巧

Android 限制EditText只能輸入數字、限制輸入型別、限制輸入長度的小技巧

準確的說讓Edittext只能輸入數字有方法兩種,都是通過xml屬性設定

方法一:

  1. <EditText
  2.            android:id="@+id/u_account"
  3.            android:layout_width="0dp"
  4.            android:layout_height="match_parent"
  5.            android:layout_marginLeft="13dp"
  6.            android:inputType="phone|number"
  7.            android:maxLength
    ="11"
  8.            android:numeric="integer"  //這個屬性限制只能輸入數字  
  9.            android:singleLine="true"
  10.            android:textColor="@color/hint_textcolor"
  11.            android:textSize="14sp"/>

方法二:
  1. <EditText
  2.            android:id="@+id/u_account"
  3.            android:layout_width="0dp"
  4.            android:layout_height
    ="match_parent"
  5.            android:background="@drawable/signup_input_pw_text_bg"
  6.            android:digits="1234567890"  //這個屬性限制只能輸入0-9這些數字</span>
  7.            android:inputType="phone|number"
  8.            android:maxLength="11"
  9.            android:singleLine="true"
  10.            android:textColor="@color/hint_textcolor"
  11.            android:textSize="14sp"/>

雖然方法一二都可以,但方法一中  android:numeric="integer"已被官方放棄,所以不推薦使用。

使用方法而更好!與時俱進嘛!

上面是以前的部落格內容;

下面補充些常用的技巧,實現方式都分為兩種:

  1. 限制輸入型別
    程式碼:et_lxnr.setInputType(InputType.TYPE_TEXT_VARIATION_LONG_MESSAGE);
    xml:android:inputType="number"
  2. 限制輸入長度(如限制輸入最大長度10)
    程式碼:et_lxnr.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
    xml:android:maxLength="10"
  3. 限制輸入固定的某些字元(如123456xyz)
    程式碼:et_lxnr.setKeyListener(DigitsKeyListener.getInstance(“123456xyz”);
    xml:android:digits="@string/input_num_character"

以上是目前知道比較常用的,以後若發現會繼續補上.