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

前端 未结 7 2053
星月不相逢
星月不相逢 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:12

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

提交回复
热议问题