Android disable space only for Edittext

自闭症网瘾萝莉.ら 提交于 2019-12-03 01:23:56
SAndroidD

her is solution work for me :

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

Add it into edit text in xml file

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

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

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
/>
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 "";
    }
}
});

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

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

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

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

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

Simple and easy way to do is:

This is will remove spaces from the text on button click:

String s = etPass.getText().toString().replaceAll(" ","");

You can use the "string s" wherever you need to.

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

Try this and it works well

kotlin:

editText.filters = arrayOf(object : InputFilter {
        override fun filter(source: CharSequence?, start: Int, end: Int, dest: Spanned?, dstart: Int, dend: Int): CharSequence? {
       // eliminates single space
           if (end == 1) {
                if (Character.isWhitespace(source?.get(0)!!)) {
                    return ""
                }
            }
            return null
        }
    })

Java:

editText.setFilters(new InputFilter[]{(source, start, end, dest, dstart, dend) -> {
        if (end == 1) {
            if (Character.isWhitespace(source.charAt(0))) {
                return "";
            }
        }
        return null;
    }});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!