Android disable space only for Edittext

2019-03-24 15:05发布

问题:

In my android application I need to disABLE Spacebar only. But I didn't find a solution for this problem. I need to disable space bar and when user enter space should not work, special characters, letters, digits and all other should work. What I tried is,

etPass.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                String str = s.toString();
                if(str.length() > 0 && str.contains(" "))
                {
                    etPass.setError("Space is not allowed");
                    etPass.setText("");
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });

But the problem here is once space comes whole text is deleting. I removed

etPass.setText("");

this line, so at that time error message is showing, but at that time user can still able to type space. But what I need is user shouldn't able to type the space.

回答1:

Why don't you think about a character filter .. Here is a sample code snippet.

/* To restrict Space Bar in Keyboard */
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;
    }

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


回答2:

her is solution work for me :

android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
android:inputType="textFilter"

Add it into edit text in xml file



回答3:

This version support input from keyboard's suggestions with spaces.

InputFilter filter = new InputFilter() {
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        String filtered = "";
        for (int i = start; i < end; i++) {
            char character = source.charAt(i);
            if (!Character.isWhitespace(character)) {
                filtered += character;
            }
        }

        return filtered;
    }

};

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

PS: Kotlin version:

input.filters = arrayOf(InputFilter { source, _, _, _, _, _ ->
    source.toString().filterNot { it.isWhitespace() }
})


回答4:

EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
new InputFilter() {
    @Override
    public CharSequence filter(CharSequence cs, int start,
                int end, Spanned spanned, int dStart, int dEnd) {
        // TODO Auto-generated method stub
        if(cs.equals("")){ // for backspace
             return cs;
        }
        if(cs.toString().matches("[a-zA-Z]+")){ // here no space character
             return cs;
        }
        return "";
    }
}
});


回答5:

Try this

Use android:digits don't include " "(space in it)

<EditText
    android:inputType="number"
    android:digits="0123456789.abcdefghijklmnl....."// write character that you want to allow
/>


回答6:

To disable space use

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (editclicked) {
        if (keyCode == KeyEvent.KEYCODE_SPACE) {
            return false
        }
    } else {
        super.onKeyDown(keyCode, event);
    }
}


回答7:

Just replace this in your code and it should work perfectly,

etPass.setText(etPass.getText().toString().replaceAll(" ",""));


回答8:

In afterTextChanged method put the following code:

  public void afterTextChanged(Editable s) {

        String str = etPass.getText().toString();
        if(str.length() > 0 && str.contains(" "))
        {
            etPass.setText(etPass.getText().toString().replaceAll(" ",""));
            etPass.setSelection(etPass.getText().length());
        }
    }


回答9:

I tried using the InputFilter solution and doesn't work for me because If try to tap backspace, the whole entered text doubles in the EditText.

This solution works for me in Kotlin using TextWatcher:

editText.addTextChangedListener(object : TextWatcher {
    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {          }

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
    }

    override fun afterTextChanged(p0: Editable?) {
        val textEntered = editText.text.toString()

        if (textEntered.isNotEmpty() && textEntered.contains(" ")) {
            editText.setText(editText.text.toString().replace(" ", ""));
            editText.setSelection(editText.text.length);
        }
    })


回答10:

instead of etPass.setText(""); just remove space from EditText data.

etPass.setText(etPass.getText().toString().trim());
etPass.setSelection(autoComplete.getText().length());

so your IF condition will be as follows :

if(str.length() > 0 && str.contains(" "))
{
    etPass.setError("Space is not allowed");
    etPass.setText(etPass.getText().toString().trim());
    etPass.setSelection(etPass.getText().length());
}