Srikanth
Srikanth

Reputation: 1575

EditText allow only alphabets, digits of all languages

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.

Upvotes: 2

Views: 3473

Answers (1)

josedlujan
josedlujan

Reputation: 5600

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

Upvotes: 2

Related Questions