Java – Detects line breaks in EditText

Detects line breaks in EditText… here is a solution to the problem.

Detects line breaks in EditText

How to detect when I press the back button on the on-screen keyboard, which creates a newline in the EditText field.

I

don’t really care if I have to check for line breaks or the back key, but I want to send a message by pressing the back key on my keyboard.

I’ve tried a few different things, but I can’t seem to get it to work.

In case you’re wondering, my EditText object is called chatInputET.

Solution

Add a listener for your input:

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

Related Problems and Solutions