用双换行符替换换行符

Replace newline with double newline

我定义了一个 EditText,我允许用户在其中输入 his/her 内容。

当用户按下换行键时,EditText 将光标移动到换行符。

我不希望这种情况发生。我想要中间的另一个空白行(如段落)。

我想我们必须为此使用 TextWatcher,但我不确定如何使用它。有人可以指导我吗?

简而言之,我想将用户输入的 \n 即时替换为 \n\n

谢谢。

首先将 textwatcher 侦听器设置为您的 edittext

// Set Text Watcher listener
myEditText.addTextChangedListener(passwordWatcher);

在您的 activity

中也包含此静态 class
private final TextWatcher passwordWatcher = new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//This means that the characters are about to be replaced with some new text.The text is uneditable. 
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            //Changes have been made, some characters have just been replaced. The text is uneditable.Use: when you need to see which characters in the text are new.
        }

        public void afterTextChanged(Editable s) {

             //Changes have been made, some characters have just been replaced. now the text is editable. please do your replacement job here
//you can get the text from the "s". compare and replace "\n" with "\n\n" 



        }
    };

请看一下这个教程:textwatcher example

虽然您想检测用户何时按下 "newline key",但我建议您使用 KeyListener 而不是 TextWatcher

yourEditText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_ENTER)  {
              // Here the user press the EnterKey (newline),
              // so you can add another extra line to your EditText.
              // Add the "\n" character to your text, to skip another line.
            }
            return false;
        }
    });