Android disable space only for Edittext

限于喜欢 提交于 2019-12-31 17:57:28

问题


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:


This solution worked for me :

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

Add it into edit text in the XML file




回答2:


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



回答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:


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
/>



回答5:


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



回答6:


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



回答7:


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



回答8:


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



回答9:


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

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



回答10:


I found very better solution instead of use digit or write any extra code , just do this things...

tiePassword.filters = tiePassword.filters.let {
        it + InputFilter { source, _, _, _, _, _ ->
            source.filterNot { char -> char.isWhitespace() }
        }
    }

it will not allow any space. try and enjoy... keep Learning and sharing




回答11:


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



回答12:


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


来源:https://stackoverflow.com/questions/33993041/android-disable-space-only-for-edittext

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