Reputation: 441
hey i want to restrict my edittext input ..i want that user cannot add any & into the edittext..is it possible? if yes please help... here is my edit text code..
EditText descriptions = new EditText(this);
allEds.add(descriptions);
descriptions.setHint("Descriptions");
descriptions.setInputType(InputType.TYPE_CLASS_TEXT);
if("0".equals(partial_check)){ descriptions.setEnabled(true); }else{ descriptions.setEnabled(false); }
linearLayout.addView(descriptions);
Upvotes: 1
Views: 1121
Reputation: 3831
I did it like by using input filter, you can change it to your needs
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++) {
String checkMe = String.valueOf(source.charAt(i));
Pattern pattern = Pattern.compile("[+0123456789]");
Matcher matcher = pattern.matcher(checkMe);
boolean valid = matcher.matches();
if(!valid){
Log.d("", "invalid");
return "";
}
}
return null;
}
};
here "[+0123456789]"
in the line Pattern pattern = Pattern.compile("[+0123456789]");
is what will be accepted.now for your edit text set this filter
yourEditTexy.setFilters(new InputFilter[]{filter});
Upvotes: 0
Reputation: 3633
descriptions.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if (s.length() > 0) {
if (s.charAt(s.length() - 1) == '&') {
descriptions.setText(s.subSequence(0, s.length() - 1));
descriptions.setSelection(s.length() - 1);
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
Upvotes: 1
Reputation: 5150
As Gautham said use OntextChangedListener for this kind of problem which will check each letter after insertion and help you to restrict. Something like:
descriptions .addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
//restrict the word here...
}
});
For some extra information about ontextChanged and TextWatcher Tutorial and also the Documentation.
Upvotes: 0
Reputation: 5166
Use an edittext Ontextchanged listener for this. There check whether the current text contains an & character. If it does, remove it and reset the edittext with the string without the & character.
This link will give you some idea of the exact usage: Counting Chars in EditText Changed Listener
Upvotes: 0