Android disable space only for Edittext
Asked Answered
T

17

43

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("");, 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.

Tadeo answered 30/11, 2015 at 7:0 Comment(1)
Check this AnswerRummage
T
84

This solution worked for me :

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

Add it into edit text in the XML file

Thebaine answered 1/8, 2016 at 7:4 Comment(4)
This answer is nice , Even the spaces can be provided for input type = number , Thank You So Much @ThebaineHluchy
What about on a Chinese keypad?Disproportion
On pressing the spacebar again, twice or more, it removes the previous characters or capitalizes themBringhurst
This solution is Locale dependent and will not work in countries without the english alphabetGiddy
S
45

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 });
Stuffing answered 30/11, 2015 at 7:5 Comment(6)
Why it is deleting the text if i am clicking the space bar to give white spaces?Nuclide
@Akshaykumar that bug must be related to something else. Code provided is working fine here.Womanly
This approach has very strange side effect (if suggestions are enabled for this EditText) - tapping space triggers like backspace. 1st entered space in the end of EditText really filters out, but next space tappings works like backspace erasing entered text which is totally weird. To avoid this side effect you could use inputType="textVisiblePassword" - with this workaround it will work.Morell
if you press multiple times to space it erases the last charLegendre
Why not just this at the beginning if (source.toString().equals(" ")) return "";Higginson
Last char erases because keyboard has this feature. Should use other way for this issueForte
D
20

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() }
})
Detradetract answered 8/7, 2016 at 13:13 Comment(3)
This approach has very strange side effect if suggestions are enabled for this EditText - if user taps BackSpace the whole entered text doubles in EditText. So instead of erasing text just grows up. Thats kinda annoying. – Stan 5 mins agoMorell
Kotlin filter is creating issue, it's removing max length configuration for password type EditText.Foresaid
@kevin This kotlin filter is not working in samsung devices, is there any solutions for samsung devicesVillain
H
7

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

Hickok answered 13/12, 2019 at 7:17 Comment(4)
this works good,Acetylene
good but duplicate characters after typing @ symbolFyrd
@OlekL. Are you got any solution for @ symbol type duplicate characters entered on the edittext.Hema
For me it works fine, without duplicating characters on '@' symbolTurpeth
B
7

Extension for remove spaces:

fun String.removeSpace() = trim().replace("\\s+".toRegex(), replacement = "")

Remove spaces for EditText enter:

val removeFilter = InputFilter { s, _, _, _, _, _ -> s.toString().removeSpace() }
editText.apply { filters = filters.plus(removeFilter) }
Benghazi answered 5/9, 2020 at 10:28 Comment(0)
S
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
/>
Sinciput answered 30/11, 2015 at 7:3 Comment(1)
just using android:inputType="number" does the work of diabling spacebarScarlatti
E
5
EditText yourEditText = (EditText) findViewById(R.id.yourEditText);
yourEditText.setFilters(new InputFilter[] {
    @Override
    public CharSequence filter(
        CharSequence cs, int start, int end,
        Spanned spanned, int dStart, int dEnd
    ) {
        /** For backspace */
        if (cs.equals("") {
             return cs;
        }

        /** Here is no space character */
        if (cs.toString().matches("[a-zA-Z]+")) {
            return cs;
        }

        return "";
    }
});
Epidemiology answered 30/11, 2015 at 7:6 Comment(0)
C
5

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);
        }
    }})
Cay answered 25/10, 2018 at 16:40 Comment(0)
F
4

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());
    }
}
Fayalite answered 3/7, 2018 at 14:42 Comment(3)
working fine when enter space at last in an edittext but when entering space in between texts, the after space texts in editext gets disappeared, any solution for this problem @FayaliteVillain
I checked this now, and it's not happened to me :\ @OmBalaFayalite
Found out what is the issue @Moti, we have give TYPE_TEXT_FLAG_NO_SUGGESTIONS in input typeVillain
M
4

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;
}});
Missal answered 23/7, 2019 at 7:2 Comment(0)
C
2

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

etPass.setText(etPass.getText().toString().replaceAll(" ",""));
etPass.setSelection(etPass.getText().length());
Charlatanry answered 30/11, 2015 at 7:13 Comment(1)
and yout can move cursor at end using this editText.setSelection(editText.getText().toString().length()Appropriate
E
1

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);
    }
}
Emrich answered 30/11, 2015 at 7:9 Comment(0)
C
0

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());
}
Catastrophism answered 30/11, 2015 at 7:4 Comment(0)
J
0

So far I discovered that this depends a lot on your keyboard which will change behavior based on return values and even delete characters assuming the last one was inserted. Also, SwiftKey may ignore textNoSuggestions, so I ended up using this InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD

etInput.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
etInput.filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend ->
    //val debugMsg = "'" + source + "' (" + start + " - " + end + ") '" + dest + "' (" + dstart + " - " + dend + ")"
    val srcChangeLength = end - start
    if (srcChangeLength <= 0) { //We're deleting a character
        //Log.d("idk", debugMsg + " -> '" + source + "'")
        return@InputFilter source
    }
    val result = if (source is SpannableStringBuilder) source else {
        //Log.d("idk", "Converted source from " + source::class.qualifiedName)
        SpannableStringBuilder(source)
    }
    for (i in end - 1 downTo start) {
        val currentChar = result[i]
        if (Character.isSpaceChar(currentChar)) {
            result.delete(i, i+1) //NOTE: You must modify or return the source. Otherwise,
            //android assumes you're inserting a string and saves the changes for the next callback(?)
        }
    }
    //Log.d("idk", debugMsg + " -> '" + result + "'")
    return@InputFilter result
})

I'm not an expert on this so I may have the wrong assumptions here, but this is working so far for me.

Jesusa answered 24/9, 2020 at 16:7 Comment(0)
T
0

The vast majority of answers do not consider the issue with the input buffer, which can cause duplicate input when the input method is in buffer mode. Here is my solution:

internal val AvoidSpaceFilter = InputFilter { source, _, _, _, _, _ ->
    val sourceText = source.toString()
    if (" " !in sourceText) return@InputFilter null // keep original
    sourceText.replace(" ", "")
}

etUsername.apply { filters += AvoidSpaceFilter }

This solution also handles pasting from the clipboard, by simply excluding scenarios where the input source does not contain any spaces.

Tautologize answered 17/2, 2023 at 9:7 Comment(0)
I
0

Try this, it worked for me

editText.addTextChangedListener(new TextWatcher() {
private boolean mSpaceDisabled = false;

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}

@Override
public void afterTextChanged(Editable s) {
    if (mSpaceDisabled) {
        mSpaceDisabled = false;
        return;
    }

    String input = s.toString();
    StringBuilder filtered = new StringBuilder();
    for (int i = 0; i < input.length(); i++) {
        char c = input.charAt(i);
        if (c == ' ') {
            mSpaceDisabled = true;
            continue;
        }
        filtered.append(c);
    }

    editText.removeTextChangedListener(this);
    editText.setText(filtered.toString());
    editText.setSelection(filtered.length());
    editText.addTextChangedListener(this);
}

});

Isa answered 28/3, 2023 at 17:32 Comment(0)
I
0

This can be solved using filters. First make a extension for removing spaces.

fun String.removeSpace() = trim().replace("\\s+".toRegex(), replacement = "")

Then use it like this:

val removeFilter = InputFilter { s, _, _, _, _, _ ->
    s.toString().removeSpace()
}
edittext.apply { filters = filters.plus(removeFilter) }

But if you have applied android:maxLength="10" then that won't work. You can then add maxLenght to the InputFilter.

val removeFilter = InputFilter { s, _, _, _, _, _ ->
    // set your limit here using take function
    s.toString().removeSpace().take(10)
}
edittext.apply { filters = filters.plus(removeFilter) }
Inaccessible answered 7/3 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.