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

徘徊边缘 提交于 2019-11-28 09:24:18

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.

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();
                    }
                }});
Harsh Dev Chandel
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

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.

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(), "");
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!