22

Hi I want to show only numbers and characters on the keypad for EditText in android, I did try to add the attribute android:inputType = text|number but it did not work.

Please help me with any other better suggestion. thanks in advance.

appersiano
  • 2,670
  • 22
  • 42
learner
  • 1,041
  • 3
  • 15
  • 31

10 Answers10

37

Use the filter for that. Here I am adding the code for filter.

  EditText etName = (EditText)findViewById(R.id.etName);
  InputFilter filter = new InputFilter() { 
        @Override
        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; 
        }
  };
  etName.setFilters(new InputFilter[]{filter}); 
pz64_
  • 2,212
  • 2
  • 20
  • 43
Aju
  • 4,597
  • 7
  • 35
  • 58
26

try to add the digits parameter to your editText:

android:digits="abcde.....012345789"
Dyonisos
  • 3,541
  • 2
  • 22
  • 25
6

The solution with InputFilter provided here is not 100% correct as it will replace and throw out some valid characters from the input if they are right next to the invalid one.

For example we need to filter out all special characters and you enter text: olala[

The EditText field will pass the whole olala[ sentence to the filter and the return value will be "" meaning that we throw out valid olala as well.

Here is my solution:

InputFilter filter = (source, start, end, dest, dstart, dend)->{
    for (int i = start; i < end; i++) {
        char symbol = source.charAt(i);
        if (!isValidCharacter(symbol)) {
            StringBuilder buf = new StringBuilder();
            for(int j = start; j < end; j++)
            {
                symbol = source.charAt(j);
                if(isValidCharacter(symbol)) buf.append(symbol);
            }
            return buf.toString();
        }
    }
    return null;
};

We need double loop here to avoid memory allocation of StringBuilder for every method call with valid characters.

pz64_
  • 2,212
  • 2
  • 20
  • 43
Northern Captain
  • 1,147
  • 3
  • 25
  • 32
  • 1
    This answer is the most suitable one, because it excludes the unwanted characters. The accepted answer, instead, just limits to allowing valid characters. – Ezequiel Adrian Sep 06 '21 at 13:27
  • Only solution that worked on all scenarios. Thanks for solution. – pz64_ Dec 10 '21 at 09:52
5

If you want to add spaces you can give space after the last digit.

 android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 "
3

try using this method it worked for me:

public static InputFilter[] getFilter(String blockChars) {
   return new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
        for (int i = start; i < end; i++) {
            if (source != null && blockChars.contains("" + source.charAt(i))) {
                return source.subSequence(start, i);
            }
        }
        return null;
    }};

add this line for your edit text

edittext.setFilters(getFilter("@~"));
Deepak
  • 127
  • 4
  • 11
1

The expected solution is to restrict user from entering special characters from keyboard.

The below solution uses RegX but adds it to strings.xml file so that will be taken care at the time of creating multilingual xmls.

Strings.xml

<string name="alpha_numeric_regx">[a-zA-Z 0-9]+</string>

Source file

 //Extracting forehand to avoid multiple calls to getString from Filter
        String alphaNumericRegX = getString(R.string.alpha_numeric_regx);
        mEditTextOtp.setFilters(new InputFilter[]{(source, start, end, dest, dStart, dEnd) -> {
            for (int i = 0; i < source.length(); i++) {
                if (source.equals("")) {
                    return source;
                }
                if (source.toString().matches(alphaNumericRegX)) {
                    return source;
                }
                return "";
            }
            return null;
        }});

Hope this will solve the prob. for new guys. :)

MobileEvangelist
  • 2,583
  • 1
  • 25
  • 36
1

Kotlin

et_search.keyListener = DigitsKeyListener.getInstance(getString(R.string.alphanumeric))

String.xml

<string name="alphanumeric">0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ</string>
Vanya Rachel
  • 1,329
  • 1
  • 18
  • 20
0
  //大兄弟,这么做就可以了。 
  InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            for (int i = start; i < end; i++) {
                if (isChineseChar(source.charAt(i))) {
                    return "";
                }
            }
            return null;
        }
    };
    etName.setFilters(new InputFilter[]{filter});

//一条简单的规则。
private static boolean isChineseChar(char c) {
    Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
    return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS;
}
dong sheng
  • 266
  • 3
  • 10
0

Its Working Restrict Special Symbol in Edittext

    private EditText your_editText ;
    private String blockCharacters = "(~*#^|$%&!";

    private InputFilter filter = new InputFilter() {

        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            if (source != null && blockCharacters.contains(("" + source))) {
                return "";
            }
            return null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        your_editText = (EditText) findViewById(R.id.your_editText);
        your_editText .setFilters(new InputFilter[] { filter });
    }

}
Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
0

I couldn't edit a previous answer, so I did a Kotlin version of it (including whitespace):

private val userNameFilter =
    InputFilter { source, start, end, dest, dStart, dEnd ->
        for (i in start until end) {
            if (!Character.isLetterOrDigit(source[i]) && !Character.isWhitespace(source[i])) {
                return@InputFilter ""
            }
        }
        null
    }
fetchSerotonin
  • 192
  • 1
  • 9