I am developing an application for keyboard, but i am geting an issue. I want to restrict/block some special character from soft keyboard in EditText in android programmatic
This should work:
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});
Or if you prefer the easy way:
<EditText android:inputType="text" android:digits="0123456789*,qwertzuiopasdfghjklyxcvbnm" />
For those who might be facing issues while adding space please add a blank space with all the alphabets. Below is an example Also you should know that user won't be able to add a new line in this case.
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:digits="0123456789,a bcdefghijklmnopqrstuvwxyz"
android:maxLines="1"
android:singleLine="true" />
You can create regular expression and check it on onTextChanged method
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
yourEditText. ...
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
Try this may work for you
public class MainActivity extends Activity {
private EditText editText;
private String blockCharacterSet = "~#^|$%&*!";
private InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText.setFilters(new InputFilter[] { filter });
}
}