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这些数字</span>
            android:inputType="phone|number"
            android:maxLength="11"
            android:singleLine="true"
            android:textColor="@color/hint_textcolor"
            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"

以上是眼下知道比較经常使用的。以后若发现会继续补上.


原文地址:https://www.cnblogs.com/lcchuguo/p/5389836.html