Disable space in EditText android

I created an EditText with the following.

<EditText
        android:id="@+id/et_regis_num"
        android:maxLines="1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:digits="1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        android:hint="@string/txt_reg_num"
        android:inputType="textCapCharacters"
        android:maxLength="10" />

in this editor, I don’t want to press the SPACE key, but when I press the SPACE key, it works like the BACKSPACE key. means that each time one character is deleted twice.

+6
source share
3 answers

Set InputFilterto EditText. Please check below the answer that worked for me.

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.isWhitespace(source.charAt(i))) {
                return "";
            }
        }
        return null;
    }
};

edtTxt.setFilters(new InputFilter[] { filter });
+5
source

Just allow the space in the edittext and replace the space with an empty one,

    @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
    }
}
+3
source
private InputFilter filter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {


        if(source.equals(" ")){
            int startSelection=editTextView.getSelectionStart();
            int endSelection=editTextView.getSelectionEnd();
            editTextView.setText(editTextView.getText().toString().trim());
            editTextView.setSelection(startSelection,endSelection);

        }

        return null;
    }
};

editTextView.setFilters(new InputFilter[] { filter });
0
source

Source: https://habr.com/ru/post/1649385/


All Articles