How do I trigger an action when the user has hit e

2019-02-22 01:37发布

问题:

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)
                {

回答1:

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
    }
});


回答2:

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



回答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.