Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 955
Jani Bela Avatar asked Mar 18 '12 11:03

Jani Bela


1 Answers

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.

like image 120
user Avatar answered Nov 16 '22 01:11

user