Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict EditText to only specified characters in android? [closed]

Tags:

android

I want to restrict my EditText to only specific characters like (a-z,A-Z,0-9,space,.and some other).

If the user tries to enter some other characters beyond the list,it should not be displayed in edittext.

Is there any way to do this?

like image 258
user2376732 Avatar asked Jun 14 '13 10:06

user2376732


2 Answers

Try this:

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}); 

Check How can I filter ListView data when typing on EditText in android

like image 72
Jainendra Avatar answered Oct 15 '22 23:10

Jainendra


Here is the solution for you....

Just add the characters to the string which you want to allowed

    final String allowed = "abcdefghijklmnopqrstuvwxyz";
    final EditText editText = (EditText)findViewById(R.id.edit001);
    editText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            char currentChar = s.charAt(start);
            System.out.println(currentChar);
            if(allowed.contains(Character.toString(currentChar)))
            {
                //Nothing to do
            }
            else
            {
                editText.setText(editText.getText().toString().substring(0, editText.getText().toString().length()-1));
                int position = editText.length();
                Editable etext = editText.getText();
                Selection.setSelection(etext, position);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub

        }
    });
like image 4
Ram kiran Pachigolla Avatar answered Oct 15 '22 23:10

Ram kiran Pachigolla