7

If (in Android) I have an EditText box, how can I trigger an event when the user has finished entering data and hits return/Next?

I have tried using the code below but it seems to have no effect. I also get an 'The method onEditorAction(EditText, int, KeyEvent) from the type new extView.OnEditorActionListener(){} is never used locally' error.

myEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
            public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_NEXT)
                {
Entropy1024
  • 7,847
  • 9
  • 30
  • 32

3 Answers3

9

I played around a bit with various things and found that the code below works:

myEditText.setOnEditorActionListener(new OnEditorActionListener() {                     
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // Do some stuff
    }
});
Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
Entropy1024
  • 7,847
  • 9
  • 30
  • 32
4

I believe you want is the setOnEditorActionListener() method, dev guide info here on the method.

Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
  • Interessting method. Never came accross this one... Will keep it in mind. – DrColossos Nov 17 '10 at 21:51
  • 1
    @DrColossos More related info about it by @CommonsWare http://stackoverflow.com/questions/1489852/android-handle-enter-in-an-edittext/1489895#1489895 – Bryan Denny Nov 17 '10 at 21:54
  • Thanks. Would that also work if someone clicked on the EditText and then clicked away. Possibly handled by a loss of focus command? – Entropy1024 Nov 17 '10 at 22:22
  • loss of focus is too unreliable..many times I run into a edittext box that won't lose focus after hitting enter. – Ted Betz Mar 17 '11 at 02:29
3

Add a KeyListener to the textbox that listens key events. Within the key event, listen to the "ENTER" key pressed and perform your action.

You can find something similar here: Android Development: How To Use onKeyUp? and in the docs for UI-Events.

A good example is in the linked SO question. Following this, you should get the desired result.

Community
  • 1
  • 1
DrColossos
  • 12,656
  • 3
  • 46
  • 67
  • As specified in the Android documentation, the default software keyboard will never send any key event to any application targeting Jelly Bean or later, and will only send events for some presses of the delete and return keys to applications targeting Ice Cream Sandwich or earlier. – Héctor Júdez Sapena May 07 '14 at 12:29