Domanda

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!

È stato utile?

Soluzione

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.

Altri suggerimenti

setSelection is there to set the cursor again at the end of your EditText:

editText.addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence cs, int arg1, int arg2,
                        int arg3) {}
                @Override
                public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                        int arg3) {}
                @Override
                public void afterTextChanged(Editable arg0) {
                    if(editText.getText().toString().contains(" ")){ editText.setText(editText.getText().toString().replaceAll(" " , ""));
                    editText.setSelection(editText.getText().length());

                    Toast.makeText(getApplicationContext(), "No Spaces Allowed", Toast.LENGTH_LONG).show();
                    }
                }});
boolean editclicked =false ;

edittext.addTextChangedListener(new TextWatcher() {
    public void afterTextChanged(Editable s) {
        editclicked = false ;
    }

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

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

Put this as a separate function:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (editclicked) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
            return false
        }
    } else {
        super.onKeyDown(keyCode, event);
    }
}
@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

My relatively simple solution for instant whitespace deletion without removing spannables (styles) in EditText:

  1. Remove at start:

        @Override
    public void afterTextChanged(Editable s) {
        int i;
        for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
        s.replace(0, i, "");
    }
    

Basically that's it, but you can also do:

  1. Remove at start (without interrupting first input):

        @Override
    public void afterTextChanged(Editable s) {
        String text = s.toString();
        if(!text.trim().isEmpty()){
            int i;
            for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
            s.replace(0, i, "");
        }
    }
    

  1. Removing at start and end (allow 1 whitespace at end for convinient input):

        @Override
    public void afterTextChanged(Editable s) {
        int i;
        //remove at start
        for (i = 0; i < s.length() && Character.isWhitespace(s.charAt(i)); i++) { ; }
        s.replace(0, i, "");
        //remove at end, but allow one whitespace character
        for (i = s.length(); i > 1 && Character.isWhitespace(s.charAt(i-1)) && Character.isWhitespace(s.charAt(i-2)); i--) { ; }
        s.replace(i, s.length(), "");
    }
    

For removing the space instantly you can achieve it by two ways.

One simple solution you can set the digits to your edit text.

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" 

second way you can set a filter

EditText.setFilters(new InputFilter[] { filter });


InputFilter filter = new InputFilter() {
 public CharSequence filter(CharSequence source, int start, int end,
   Spanned dest, int dstart, int dend) {
  for (int i = start; i < end; i++) {
   if (Character.isSpaceChar(source.charAt(i))) {
    return "";
   }
  }
  return null;


      }
     }

One more simple way to achieve this using the input Filter

editText.setFilters(new InputFilter[]{new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.toString().equalsIgnoreCase(" ")){
                return "";
            }
            return source;
        }
    }});

This will remove the space entered by the user immediately and gives appearance like space is disabled.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top