Sunday, April 22, 2012

How do I use InputFilter to limit characters in an EditText in Android?


I want to restrict the chars to 0-9, a-z, A-Z and spacebar only. Setting inputtype I can limit to digits but I cannot figure out the ways of Inputfilter looking through the docs.



Source: Tips4all

4 comments:

  1. found this on another forum. works like a champ.

    InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end,
    Spanned dest, int dstart, int dend) {
    for (int i = start; i < end; i++) {
    if (!Character.isLetterOrDigit(source.charAt(i))) {
    return "";
    }
    }
    return null;
    }
    };

    edit.setFilters(new InputFilter[]{filter});

    ReplyDelete
  2. In addition to the accepted answer, it is also possible to use e.g.: android:inputType="textCapCharacters" as an attribute of <EditText> in order to only accept upper case characters (and numbers).

    ReplyDelete
  3. If you subclass InputFilter you can create your own InputFilter that would filter out any non-alpha-numeric characters.

    The InputFilter Interface has one method, filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend), and it provides you with all the information you need to know about which characters were entered into the EditText it is assigned to.

    Once you have created your own InputFilter, you can assign it to the EditText by calling setFilters(...).

    http://developer.android.com/reference/android/text/InputFilter.html#filter(java.lang.CharSequence, int, int, android.text.Spanned, int, int)

    ReplyDelete
  4. It is possible to use setOnKeyListener. In this method, we can customize the input edittext !

    ReplyDelete