2

I have an EditText in which i want to allow only alphabets and numbers of any language. I tried with different android:inputType and android:digits in XML.

I tried with set TextWatcher to edittext in which onTextChanged() is like

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

        switch (et.getId()) {
        case R.id.edtMultiLang: {
            et.removeTextChangedListener(watcher2);
            et.setText(s.toString().replaceAll("[^[:alpha:]0-9 ]", ""));
            // et.setText(s.toString().replaceAll("[^A-Za-z0-9 ]", ""));
            et.addTextChangedListener(watcher2);
            break;
        }
        }
    }

This is working fine. But whenever i tried to clear text, cursor is moving to start for every letter. Means when i clear a single letter, cursor moving to start.

If i use like android:digits="abcdefghijklmnopqrstuvwxyz1234567890 ", it allows me to type only alphabets and numbers of english. It is not allowing me to enter any other language text As i given only English related alphabets here. But my requirement is to allow copy/paste of other language's alphabets and letters also. I hope we can do this by using Patterns, TextWatcher and InputFilter. But i didn't find better way.

Please let me know if there any way to do this.

Srikanth
  • 1,555
  • 12
  • 20
  • I found solution at http://stackoverflow.com/questions/41953259/edittext-cursor-coming-to-start-for-every-letter-when-clear-text , but when i paste text, cursor moving to end – Srikanth Feb 01 '17 at 05:02

1 Answers1

2

The option you mention to resolve the problem is easy and fast, if you use a filter your code will be like this:

public static InputFilter filter = new InputFilter() {
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String blockCharacterSet = "~#^|$%*!@/()-'\":;,?{}=!$^';,?×÷<>{}€£¥₩%~`¤♡♥_|《》¡¿°•○●□■◇◆♧♣▲▼▶◀↑↓←→☆★▪:-);-):-D:-(:'(:O 1234567890";
        if (source != null && blockCharacterSet.contains(("" + source))) {
            return "";
        }
        return null;
    }
};

editText.setFilters(new InputFilter[] { filter });
josedlujan
  • 5,357
  • 2
  • 27
  • 49
  • thanks for reply josedlujan. In this we need to listout all special characters. we need to consider smilies also. – Srikanth Jan 30 '17 at 13:04
  • Also while copy, pasting text in edittext, it is not restricting these blocked symbols. – Srikanth Jan 30 '17 at 13:36
  • source can contain few symbols if you type it fast. The above code is not working for that case. You should split source per chars before doing replacements. – Alex P Nov 26 '20 at 13:53