I want to restrict my EditText to only specific characters like (a-z,A-Z,0-9,space,.and some other).
If the user tries to enter some other characters beyond the list,it should not be displayed in edittext.
Is there any way to do this?
Try this:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetterOrDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[]{filter});
Check How can I filter ListView data when typing on EditText in android
Here is the solution for you....
Just add the characters to the string which you want to allowed
final String allowed = "abcdefghijklmnopqrstuvwxyz";
final EditText editText = (EditText)findViewById(R.id.edit001);
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
char currentChar = s.charAt(start);
System.out.println(currentChar);
if(allowed.contains(Character.toString(currentChar)))
{
//Nothing to do
}
else
{
editText.setText(editText.getText().toString().substring(0, editText.getText().toString().length()-1));
int position = editText.length();
Editable etext = editText.getText();
Selection.setSelection(etext, position);
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With