Android 限制EditText只能输入数字、限制输入类型、限制输入长度的小技巧

来源:互联网 发布:兼职淘宝新媒体编辑 编辑:程序博客网 时间:2024/05/01 21:52

准确的说让Edittext只能输入数字有方法两种,都是通过xml属性设置

方法一:

[html] view plain copy
  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" />  

方法二:

[html] view plain copy
  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"
0 1
原创粉丝点击