How to delete instantly SPACE from an edittext if a user presses the space?

前端 未结 7 2032
星月不相逢
星月不相逢 2020-12-09 22:44

I have an edittext, and a textwatcher that watches if SPACE arrived or not. If its a SPACE I would like to delete that instantly. Or if its a space I want to make sure it do

7条回答
  •  粉色の甜心
    2020-12-09 23:11

    @Override
    public void afterTextChanged(Editable s) {
        String result = s.toString().replaceAll("\\s", "");
        if (!s.toString().equals(result)) {
            int pos = editText.getSelectionStart() - (s.length() - result.length());
            editText.setText(result);
            editText.setSelection(Math.max(0,Math.min(pos, result.length())));
            editText.setError("No spaces allowed");
        }
    }
    

    \s matches any whitespace character (equal to [\r\n\t\f\v ])

    Setting selection like this, allow you to enter or paste text in middle of edittext without loosing cursor position

提交回复
热议问题