how to allow only specific number in edittext?

删除回忆录丶 提交于 2019-12-23 15:50:31

问题


am trying to put only a specific value in my edit text. I have used this this my layout. android:digits="0123468" however, i also do not want that number 1 and 3 should work in my edit text.

Sample; enter 32... it gives me a list of items but enter 3 should not allow me to do something.

Can someone help me on this?


回答1:


This could be an aproach:

<EditText
android:id="@+id/edtNumber"
android:digits="0123456789"
android:inputType="number" />

And if you want to discard '1' and '3' you could get input number like this:

Integer.parseInt(edtNumber.getText().toString())

and compare it with values you don't want.


Also if for some reason you want to use decimals do this:

<EditText
android:id="@+id/edtNumberDecimal"
android:digits="0123456789."
android:inputType="numberDecimal" />



回答2:


Use regular expressions.

@Override
public void afterTextChanged(Editable s) {
      String text = s.toString();
      int length = text.length();

      Pattern pattern
        = Pattern.compile("(?s)\\d|[024-9]{2,}");

      if(length > 0 && !Pattern.matches(pattern, text)) {
           s.delete(length - 1, length);
      }
}


来源:https://stackoverflow.com/questions/36337953/how-to-allow-only-specific-number-in-edittext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!