General operation is given a InputFilter, and then to add EditText controls associated resolve as follows:
step1:
// 禁止EditText输入空格
private InputFilter filter = (source, start, end, dest, dstart, dend) -> {
if (source.equals(" ")) return "";
else return null;
};
step2:
pwdEdt.setFilters(new InputFilter[]{filter});
But, today met a case of this InputFilter so bad, and looking for a long time because of the conflict in android:inputType="textPassword"
this property, and when my EditText box InputFilter used as the password does not work, can only get awkward TextWatcher , a little more than a few lines of code:
TextWatcher textChanged = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
// 禁止EditText输入空格
if (charSequence.toString().contains(" ")) {
String[] str = charSequence.toString().split(" ");
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length; i++) {
sb.append(str[i]);
}
pwdEdt.setText(sb.toString());
pwdEdt.setSelection(start);
}
}
@Override
public void afterTextChanged(Editable editable) {
}
};
Then pwdEdt.addTextChangedListener(textChanged);
add the association resolved.