Android:在输入密钥后试图摆脱返回按下TextView

时间:2012-08-29 17:45:13

标签: android

我有按下输入时删除键盘的代码。现在的问题是EditView插入了一个新行。我试图从textview获取文本并删除任何cartrige返回。但它不起作用。

这是代码:

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

2 个答案:

答案 0 :(得分:1)

首先,我不会依赖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正则表达式或自己运行代码,但它绝对是一个起点。

答案 1 :(得分:0)

要将输入限制为仅一行,请使用

mUserName.setLines(1);
mUserName.setMaxLines(1);

mUserName.setSingleLine(true);

相关问题