Android 仅对 Edittext 禁用 space

Android disable space only for Edittext

在我的 android 应用程序中,我只需要禁用空格键。但是我没有找到解决这个问题的方法。我需要禁用 space 栏,当用户输入 space 不应该工作时,特殊字符、字母、数字和所有其他应该工作。我试过的是,

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

            }
        });

但是这里的问题是一旦space来整个文本都在删除。我删除了

etPass.setText("");

这一行,所以当时显示错误消息,但此时用户仍然可以输入 space。但我需要的是用户不能输入 space.

试试这个

使用android:digits不要包含“”(space在里面)

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

而不是 etPass.setText(""); 只需从 EditText 数据中删除 space。

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

所以您的 IF 条件如下:

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

你为什么不考虑字符过滤器..这是一个示例代码片段。

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

禁用space使用

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

只需在您的代码中替换它,它应该可以完美运行,

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

此版本支持输入带空格的键盘建议。

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 版本:

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

这个解决方案对我有用:

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

将其添加到 XML 文件的编辑文本中

在 afterTextChanged 方法中放入以下代码:

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

我尝试使用 InputFilter 解决方案但对我不起作用,因为如果尝试点击退格键,整个输入的文本会在 EditText 中加倍。

此解决方案适用于 Kotlin 使用 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);
        }
    }})

试试这个,效果很好

科特林:

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

我找到了更好的解决方案而不是使用数字或编写任何额外的代码,只需执行此操作...

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

它将不允许任何 space。尝试并享受...继续学习和分享

删除空格的扩展名:

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

删除 editText 输入的空格:

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

到目前为止,我发现这在很大程度上取决于您的键盘,它会根据 return 值改变行为,甚至假设插入最后一个字符时删除字符。此外,SwiftKey 可能会忽略 textNoSuggestions,所以我最终使用了这个 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
})

我不是这方面的专家,所以我在这里的假设可能是错误的,但到目前为止这对我有用。