mahdi pishguy mahdi pishguy - 4 months ago 9
Android Question

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

i'm trying to implementing simple logic to accept only characters between

a-z
and
A-Z
programmatically

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

Answer

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