EditText控制禁止输入空格及回车
时间: 2024-02-01 19:14:20 浏览: 57
你可以通过监听EditText的输入事件,判断输入的字符是否为空格或回车,如果是,则不允许输入。
以下是一个简单的示例代码:
```
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ENTER) {
return true; // 不允许输入空格和回车
}
return false;
}
});
```
除此之外,你还可以在EditText的TextWatcher中实现类似的功能:
```
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String input = s.toString();
if (input.contains(" ") || input.contains("\n")) {
editText.setText(input.replace(" ", "").replace("\n", ""));
editText.setSelection(editText.getText().length());
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
```
这个方法会在每次输入字符后,检查EditText中是否包含空格或回车,如果包含,则将其去除,并将EditText的光标移动到最后。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)