用双换行替换换行符

时间:2015-08-23 11:47:48

标签: android android-edittext textwatcher

我定义了EditText,其中我允许用户输入他/她的内容。

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

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

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

简而言之,我希望将用户输入的\n替换为动态\n\n

谢谢。

2 个答案:

答案 0 :(得分:0)

首先将文本观察者监听器设置为您的editext

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

还在您的活动中包含此静态类

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

答案 1 :(得分:0)

虽然您想要检测用户何时按下“换行符”,但我建议您使用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;
        }
    });
相关问题