2

Please don't hurry to mark this message as "duplicated". I can't find an appropriate example. Suppose I'd like to restrict the char "{" in editText.

Let's consider a few variants of my code. I tried them on emulator only.

       editName.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
            String txt=s.toString();
            int len=txt.length();
            toastDebug("len="+myIntToStr(len));
            if (len>0) {
                try {
                    int pos=txt.indexOf("{");
                    if (pos>=0) s.replace(pos,pos+1,"");
                }
                catch(Exception e) {}
            }
        }

If I type "{" quiickly it leads to "stackOverFlow" crash. Suppose I type "abcd{{{{{{{" slowly. For the first view it looks okay, no "{" in editText. But if I type backspace, it does not remove "abcd", it removes those invisible "{{{{{"

I tried to change the editText inside of "afterTextChanged". The code below causes stackOverflowError again.

            public void afterTextChanged(Editable s) {
            String txt=s.toString();
            int len=txt.length();
            if (len>0) {
                try {
                   editName.setText(txt)
                   or
                   s.clear
                   s.append(txt)
                }
                catch(Exception e) {}
            }
        }

Many examples with code like this clear my editText after I type "{".

Well, I modified this code as follows:

    editName.setFilters(new InputFilter[] { filterName });

    private InputFilter filterName = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (source==null) return null;
            return source.toString().replace("{","");
    }
};

Now it works. But my android:maxLength="25" does not work. It is possible to type any numbers of characters.

So I am puzzled how can I restrict simple character in editText. Any ideas? Thanks!

Community
  • 1
  • 1
Niaz
  • 545
  • 2
  • 12
  • 21
  • Does this help you http://stackoverflow.com/questions/9757991/how-to-delete-instantly-space-from-an-edittext-if-a-user-presses-the-space ? – user Sep 20 '14 at 08:57
  • @Niaz , have you tried with regular expressions? – Gödel77 Sep 20 '14 at 14:08
  • Luksprog, as I said, if I change editText inside of afterTextChanged block (like in example you mentioned), I got "stackoverflow". Yes. It is only replace chars in editable to space. But if I replace "{" to "", then I got strange behaviour of backspace – Niaz Sep 21 '14 at 04:39
  • Gödel77, I could not understand the thought concerning regular expresions. – Niaz Sep 21 '14 at 04:41
  • I've run some tests with the code I linked to and it works, it wouldn't allow you to input the `"{"` character(I also don't get any exception no matter how fast I enter characters, the delete process works). The only change was to escape `{` because it will be used in a regular exception, so instead of "{" it will be "\\{". – user Sep 21 '14 at 06:20
  • Luksprog, Wow! your example really works okay! There is "replaceAll" in your example instead of "replace" in mine. I try to understand... Thank you very much for help! If you place this code as an answer, I will check it as valid. public void afterTextChanged(Editable s) { String result = s.toString().replaceAll("\\{", ""); if (!s.toString().equals(result)) { editName.setText(result); editName.setSelection(result.length()); } – Niaz Sep 21 '14 at 08:32

5 Answers5

5

You can restrict the characters that the user can enter in the EditText by setting a TextWatcher on the widget and inserting the logic below:

// we are interested in this callback
@Override
public void afterTextChanged(Editable s) {
    String result = s.toString().replaceAll("\\{", "");
    if (!s.toString().equals(result)) {
         edit.setText(result); // "edit" being the EditText on which the TextWatcher was set
         edit.setSelection(result.length()); // to set the cursor at the end of the current text             
    }
}

The \\ is required(and for other characters) because the { character has a special meaning in a pattern.

user
  • 86,916
  • 18
  • 197
  • 190
0

You can use it by xml as well

android:digits="0,1,2,3,4,5,6,7,8,9,.,@,qwertzuiopasdfghjklyxcvbnm"

or

android:digits="abcdefghijklmnopqrstuvwxyz1234567890 "

Which u want put here.

Aniruddh Parihar
  • 3,072
  • 3
  • 21
  • 39
  • thanks, I know about such solution but it does not work for other (than English) languages – Niaz Sep 20 '14 at 09:47
  • Maybe UTF8 chars works for other languages in digit="...", but it would be more comfortable to exclude couple characters, than to set all available set of chars – Niaz Sep 20 '14 at 10:38
0

My assumption is android:maxLength actually is a InputFilter that added to your EditText. so if you want to add more InputFilter, you must get the current InputFilter array of your EditText and append it with your own InputFIlter. I do this and this works.

EditText editName = (EditText) findViewById(R.id.editText1);

        InputFilter filterName = new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source==null) return null;
            return source.toString().replace("{","");
        }
    };

    //Get current Input Filter from EditText
    InputFilter[] oldInputFilter = editName.getFilters();
    //Create arrays for new InputFilter
    InputFilter[] newInputFilter = new InputFilter[oldInputFilter.length+1];
    //Copy all old Input Filter to new one
    System.arraycopy(oldInputFilter, 0, newInputFilter, 0, oldInputFilter.length);
    //Add your own input filter
    newInputFilter[newInputFilter.length-1] = filterName;
    //Set the new Input Filter
    editName.setFilters(newInputFilter);
Octaviano Putra
  • 624
  • 4
  • 9
  • Unfortunately length of editText is still unlimited and after typing abcd{{{{{{{{{{{{{{{ backspace does not remove dbca, but only these invisible {{{{{{{ somewhere... – Niaz Sep 20 '14 at 09:52
  • Are you still using the TextWatcher from first and second code? – Octaviano Putra Sep 20 '14 at 10:04
  • Are you already commented the editName.setFilters(new InputFilter[] { filterName }); from third code? – Octaviano Putra Sep 20 '14 at 10:46
  • Oh, yes. I have commented it now. The maxlength of editText is okay, but strange backspace is still there. Frankly I could not understand your code... If I replace "{" with space, all is okay, but extra spaces were added... – Niaz Sep 20 '14 at 11:47
  • Bad news is that Arrays.copyOf in your code does not work on Android 2.2. But my goal was to write an app for all Android versions.... – Niaz Sep 20 '14 at 13:15
  • I have replaced the Arrays.copyOf to alternative method. – Octaviano Putra Sep 20 '14 at 13:51
0
The above correct answer only work for one EditText.
But this work for all the EditText in you XML.

        InputFilter filter = new InputFilter() { 
            boolean canEnterSpace = false;

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

                if(_edtUsername.getText().toString().equals(""))
                {
                    canEnterSpace = false;
                }

                StringBuilder builder = new StringBuilder();

                for (int i = start; i < end; i++) { 
                    char currentChar = source.charAt(i);

                    if (Character.isLetterOrDigit(currentChar) || currentChar == '{') {
                        builder.append(currentChar);
                        canEnterSpace = false;
                    }

                    if(Character.isWhitespace(currentChar) && canEnterSpace) {
                        builder.append(currentChar);
                    }


                }
                return builder.toString();          
            }

        };
        _edtUsername.setFilters(new InputFilter[]{filter});
        _edtFirstName.setFilters(new InputFilter[]{filter});
        _edtLastName.setFilters(new InputFilter[]{filter});

Thanks

0

Here I replaced with ".com" to ""

Xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.edittextdemo.MainActivity" >

    <EditText
        android:id="@+id/edt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

// Java

public class MainActivity extends Activity {

    private EditText edt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        edt = (EditText) findViewById(R.id.edt);
        edt.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                String currentStr = s.toString().replaceAll(".com", "");
                if (!s.toString().equals(currentStr)) {
                    edt.setText(currentStr); 
                    edt.setSelection(currentStr.length());              
                }
            }
        });
    }
Hiren Patel
  • 52,124
  • 21
  • 173
  • 151