1

I'm developing a chat app, and looking for a way to catch ENTER is pressed on soft keyboard during message editing (in an EditText). The aim is to send the text directly. Obviously I also have implemented a "SEND" button.

Two attempts:

  1. using editText.addTextChangedListener(new TextWatcher()..

    Result: I get "\n" character either in onTextChanged and afterTextChanged
    callbacks. I could "remove" this character and send chat, but I don't like
    this way.

  2. using editText.setOnEditorActionListener(new TextView.OnEditorActionListener()..

    Result: It doesn't work.

Any better solution?

MBDevelop
  • 103
  • 1
  • 11
  • 2
    Possible duplicate of http://stackoverflow.com/questions/1489852/android-handle-enter-in-an-edittext – kgandroid Sep 07 '16 at 12:52
  • in above link, chosen answer extract: "..setOnEditorActionListener() method, all on TextView", but I'm using EditText – MBDevelop Sep 07 '16 at 13:02
  • Have you looked at all the famous chat applications? I just looked at FBs Messagner, Whatsapp, IMO and Skype. They all provide a separate Send button in the app. Now adding `android:imeOptions="actionSend"` as suggested by @Amy may provide means for you to achieve what you are looking for (I have never tried) but you won't be able to add a new line in your chat. – Abbas Sep 07 '16 at 13:05

2 Answers2

4

I use this to catch the soft keyboard enter and it works great, but I'm not sure is this suitable for you :

editText.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_ENTER && keyEvent.getAction() == KeyEvent.ACTION_UP) {
            //do something.
            return true;
        }
        return false;
    }
});
L. Swifter
  • 3,179
  • 28
  • 52
0

Try this;

editText.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
        {
            switch (keyCode)
            {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    //Perform Your action
                    return true;
                default:
                    break;
            }
        }
        return false;
    }
});
Amy
  • 4,034
  • 1
  • 20
  • 34
  • But, from Android Developers: "Interface definition for a callback to be invoked when a hardware key event is dispatched to this view. The callback will be invoked before the key event is given to the view. This is only useful for hardware keyboards; a software input method has no obligation to trigger this listener." I need and advice about soft keyboard. – MBDevelop Sep 07 '16 at 12:53
  • then you can use `android:imeOptions="actionSend"` in xml. – Amy Sep 07 '16 at 12:56
  • will never work, you cannot get soft keypad input events in android – Aman Grover Sep 07 '16 at 13:13