Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android EditText 輸入限制技巧:僅數字、輸入類型與長度控制

編輯:Android 程式設計入門

控制 EditText 的輸入行為是表單開發中的常見需求。準確地說,讓 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="11" 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="match_parent" android:background="@drawable/signup_input_pw_text_bg" android:digits="1234567890" //這個屬性限制僅僅能輸入0-9這些數字 android:inputType="phone|number" android:maxLength="11" android:singleLine="true" android:textColor="@color/hint_textcolor" android:textSize="14sp" />

儘管方法一、二都能達到目的,但方法一中的 android:numeric="integer" 已被官方放棄,所以不推薦使用,用法二更好!與時俱進嘛!

以上是曾經的博客內容,以下補充一些經常使用的技巧,實現方式都分為代碼與 xml 兩種:

  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"

以上是眼下知道比較經常使用的,以後若發現會繼續補上。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved