1

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.

Richard Russell
  • 1,105
  • 1
  • 10
  • 19
  • Check this question, it may help: http://stackoverflow.com/questions/2004344/android-edittext-imeoptions-done-track-finish-typing – Flávio Faria Dec 06 '12 at 12:25
  • I've seen that one, which is how I ended up with setting android:inputType="text" (following some documentation after reading that question). It seems to work. However, it's far from clear what the "right" way of doing this is. Should "onEditorAction" be used instead of "onKey"? Would this work for all devices? – Richard Russell Dec 06 '12 at 17:39

1 Answers1

1

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

Richard Russell
  • 1,105
  • 1
  • 10
  • 19