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

Jani Bela picture Jani Bela · Mar 18, 2012 · Viewed 21.7k times · Source

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 doesnt appear but indicate somehow (seterror, toast) for the user that space is not allowed.

edittext.addTextChangedListener(new TextWatcher() {

    public void afterTextChanged(Editable s) {

                   //---//
                  }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    public void onTextChanged(CharSequence s, int start, int before, int count) {}
        }); 

I cannot define onkeydown in the afterTextChaned method, since it gives me an error.

 public boolean onKeyDown(int keyCode, KeyEvent event) {
                super.onKeyDown(keyCode, event);

                if (keyCode == KeyEvent.KEYCODE_SPACE) {

                }
    }

So it is not working (syntax error, misplaced construct for the int keyCode.

Thanks you in advance!

Answer

user picture user · Mar 18, 2012

The solution is as usually much simpler:

@Override
public void afterTextChanged(Editable s) {
    String result = s.toString().replaceAll(" ", "");
    if (!s.toString().equals(result)) {
         ed.setText(result);
         ed.setSelection(result.length());
         // alert the user
    }
}

This shouldn't have the problems of the previous attempts.