Java 检测EditText中的换行符

Java 检测EditText中的换行符,java,android,android-edittext,Java,Android,Android Edittext,当我按下屏幕键盘上的return(返回)按钮在EditText(编辑文本)字段中创建换行符时,如何检测 我真的不在乎是否需要检查换行符或返回键,但我想通过按键盘上的返回键发送消息 我已经尝试了一些不同的方法,但似乎无法奏效 如果您想知道,我的EditText对象称为chatInputET。将侦听器添加到您的输入: chatInputET.addTextChangedListener( new TextWatcher(){ @Override public void onTextChang

当我按下屏幕键盘上的return(返回)按钮在EditText(编辑文本)字段中创建换行符时,如何检测

我真的不在乎是否需要检查换行符或返回键,但我想通过按键盘上的返回键发送消息

我已经尝试了一些不同的方法,但似乎无法奏效


如果您想知道,我的EditText对象称为
chatInputET

将侦听器添加到您的输入:

chatInputET.addTextChangedListener( new TextWatcher(){
  @Override
  public void onTextChanged( CharSequence txt, int start, int before, int count ) {
    if( -1 != txt.toString().indexOf("\n") ){
      doSendMsg();
    }
  }
} );

这是我想到的。我在设置editText时将其放入onCreate中

editText          = (EditText) findViewById(R.id.editText1);
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String string       = s.toString();
        if (string.length() > 0 && string.charAt(string.length() - 1) == '\n') {
            // do stuff
            // for me i get the string and write to a usb serial port
            String data     = editText.getText().toString();
            if (usbService != null)
            {
                // if UsbService was correctly binded, Send data
                usbService.write(data.getBytes());
                editText.setText("");//i clear it.
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

应该是
txt.toString().indexOf(“\n”)
,但无论如何还是要感谢:)甚至可以是
txt.toString().contains(“\n”)
您的if有一些问题,它也适用于空格字符,不仅适用于新行下面的答案是正确的if-->if(string.length()>0&&string.charAt(string.length()-1)='\n')
editText          = (EditText) findViewById(R.id.editText1);
editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String string       = s.toString();
        if (string.length() > 0 && string.charAt(string.length() - 1) == '\n') {
            // do stuff
            // for me i get the string and write to a usb serial port
            String data     = editText.getText().toString();
            if (usbService != null)
            {
                // if UsbService was correctly binded, Send data
                usbService.write(data.getBytes());
                editText.setText("");//i clear it.
            }
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});