【问题标题】:Remove new line from EditText in Android从 Android 中的 EditText 中删除新行
【发布时间】:2016-05-23 06:15:34
【问题描述】:

我有一个EditText,它应该在打字时有多行,并且在按下回车时应该有一个动作,这意味着软键盘应该消失并且光标不可见......基本上EditText应该失去“焦点”。

现在这已经完成并且可以工作了,但问题是“enter”键在EditText 中留下了一个新行。

我试图通过将整个文本设置为 "" 来删除它,但 EditText 是空白的,并带有一个新行。

我已尝试通过将 '\n' 替换为 's' 并将文本设置回来来删除它,但文本从新行开始。

String cap = caption.getText().toString().replace('\n', 's').trim();
caption.setText(cap);

提前致谢。

【问题讨论】:

  • 为什么不设置对应EditText视图的onClick监听呢?试试看,应该可以的。
  • 为什么要在编辑的时候去掉空格,我建议使用trim函数把多余的空格去掉
  • 感谢大家的回复。我需要有一个在按 Enter 时不显示新行的编辑文本。

标签: android android-edittext enter


【解决方案1】:

我知道这是一个迟到的答案,但也许它可以帮助某人。

我最近遇到了这个问题,我通过在我的EditText 上实现addTextChangedListener 解决了这个问题。

代码:

EditText editText = new EditText(this);
layout.addView(editText);
editText.addTextChangedListener(new TextWatcher() {
    boolean ignore = false; // This is used to prevent infinite recursion in the afterTextChanged method

    @Override
    public void afterTextChanged(Editable arg0) {
        if (ignore) return;

        ignore = true;

        String s = arg0.toString();
        if (s.length() > 0) {
            // The condition checks if the last typed char's ASCII value is equal to 10, which is the new line decimal value
            if (((int)(s.charAt(s.length()-1)) == 10)) {
                String newStr = s.substring(0, s.length()-1); // Removes the new line character from the string
                editText.setText(newStr);
                editText.setSelection(editText.length()); // Sets the text cursor to the end of the text
            }
        }

        ignore = false;
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
    }

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

可能有更好的方法来摆脱换行符,但这对我有用,而且看起来很简单。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 1970-01-01
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2019-06-20
    相关资源
    最近更新 更多