常规操作是定一个InputFilter,然后给EditText控件添加关联解决如下:
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,今天遇到个情况这个InputFilter不好使了,找了半天原因是冲突在android:inputType="textPassword"
这个属性上了,当我的EditText作为密码框使用的时候InputFilter不起作用了,只能用笨办法TextWatcher搞定了,代码稍微多几行:
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) {
}
};
然后pwdEdt.addTextChangedListener(textChanged);
添加关联解决。