Using a text observer is much simpler:
At class level:
EditText editText;
in onCreate:
editText = (EditText)findViewById(R.id.yourEdittext) editText.addTextChangedListener(mTextEditorWatcher);
Outside onCreate (Class Level):
final TextWatcher mTextEditorWatcher = new TextWatcher(){ public void beforeTextChanged(CharSequence s, int start, int count, int after) { } public void onTextChanged(CharSequence s, int start, int before, int count) { System.out.println("Entered text: "+editText.getText());
If you want to limit the entry in the text editor to alphabets only, add this to the XML of your text control:
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
If you don't like the above and want to achieve this with code, use the following:
editText.setFilters(new InputFilter[] { new InputFilter() { public CharSequence filter(CharSequence chr, int start, int end, Spanned dst, int dstart, int dend) { if(chr.equals("")){ return chr; } if(chr.toString().matches("[a-zA-Z ]+")){ return chr; } return ""; } } });
source share