我有代码可以在按下回车键时移除键盘。现在的问题是 EditView 插入了新行。我试图从 textview 中获取文本并删除任何墨盒返回。但它不起作用。
代码如下:
mUserName.setOnEditorActionListener(
new android.widget.TextView.OnEditorActionListener()
{
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mUserName.getWindowToken(), 0);
CharSequence c=v.getText();
String h= c.toString();
v.setText(h.replaceAll("\n",""));
return false;
}
}
);
最佳答案
首先,我不会依赖 OnEditorActionListener
。有更好的方法来做你正在寻找的事情。我建议您可以做三件事:
- 设置字段的 IME 选项。
- 将行数设置为 1。
- 改用
TextWatcher
。 (可选,不应该是必需的)
设置IME options (摆脱 Enter 按钮),使用以下内容:
mUserName.setImeOptions(EditorInfo.IME_ACTION_NONE);
接下来,您可以强制行数为 1:
mUserName.setLines(1);
mUserName.setMaxLines(1);
如果这些都不起作用(它们应该起作用),您可以使用 TextWatcher
来移除换行符:
mUserName.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Here, CHECK if it contains \r OR \n, then replaceAll
// Checking is very important so you do not get an infinite loop
if (s.toString().contains("\r") || s.toString().contains("\n")) {
s = s.replaceAll("[\r|\n]", "");
mUserName.setText(s);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Nothing
}
public void afterTextChanged(Editable s) {
// Nothing
}
});
您可能需要尝试一下这个设置,我没有测试过 replaceAll
正则表达式或自己运行代码,但这绝对是一个起点。
关于Android:在TextView上按下回车键后试图摆脱回车,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12183609/