Android: Limiting EditText to alphanumerics in any language
I want to allow users to create a username using only alphanumeric characters but where the alpha characters can be any of the characters in the user's native language. It must be possible 开发者_运维技巧to restrict the input to only those characters that are part of the alphabet of the native language or if there is no alphabet in a language (like Chinese), then limited to those characters that would normally be considered non-symbolic (symbolic characters being a question mark, colon, etc).
Using inputType seems to pose a problem because setting it to "text" actually allows the keyboard to display symbols as well.
EditText editText = (EditText)findViewById(R.id.your_edit_text);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
// 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 onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
for(int i=0;i<arg0.toString().length();i++){
if(arg0.toString().charAt(i)=='a char you hate')
//Show an error and change the contents of arg0
}
}
});
EDITED
I have edited the answer a little bit because In the previous version assumed that he changed the last character. However this is not true onTextChanged
is called even if he inserted a character in the middle of the String.
精彩评论