Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android accept only characters between a-z and A-Z

I am trying to implementing simple logic to accept only characters between a-z and A-Z programmatically

A simple solution is:

<EditText
    android:id="@+id/LanguageText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="text"
    android:digits="@string/app_lan" />

In Strings.xml :

<string name="app_lan">abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ</string>

But I want to implement that programmatically

username.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        if (s.toString().length() > 0) {
            /* if char is not between a-z and A-Z then return*/
            if ((int) s.toString().charAt(0) < 65 && (int) s.toString().charAt(0) > 90 || (int) s.toString().charAt(0) < 97 && (int) s.toString().charAt(0) > 122) {
                return;
            }else{
                /* Accept character */
            }
        }
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
});
like image 945
mahdi pishguy Avatar asked Aug 01 '16 10:08

mahdi pishguy


1 Answers

You should use InputFilters

edittext.setFilters(new InputFilter[] {
    new InputFilter() {
        public CharSequence filter(CharSequence src, int start,
                int end, Spanned dst, int dstart, int dend) {
            if(src.toString().matches("[a-zA-Z ]+")){
                return src;
            }
            return "";
        }
    }
});
like image 90
Mujammil Ahamed Avatar answered Oct 20 '22 02:10

Mujammil Ahamed