How do I detect the "enter" character when editing using a soft keyboard in an EditText on Android Jelly Bean?

StackOverflow https://stackoverflow.com/questions/13743540

Question

I have an EditText, and am attempting to listen for keystrokes with setOnKeyListener, so that when I detect an Enter keypress, it performs some action. It works fine with hard keyboards and emulators, but not on my Galaxy Nexus.

The documentation for setOnKeyListener says "Key presses in software input methods will generally not trigger the methods of this listener", which explains why not.

I don't want to explicitly add a "Done" button onscreen as in the Building Your First App tutorial.

I've now set it up to use the android:inputType="text" property in the layout xml, and it seems to have the desired effect. Is this considered the correct approach? Is it documented anywhere? Will it work on all devices? Is there a better way?

Here is the code I'm using in my Activity:

    myEditText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) 
                if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                  (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Process the entered text here
                    myEditText.setText("");
                    return true;
                }
            return false;
        }
    }

This is based on the ToDo List Example in Chapter 4 of Professional Android 4 Application Development.

Was it helpful?

Solution

It appears that android:inputType="text" is indeed the correct approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top