8

I have declared an EditText programmatically (i.e. not in XML), and want to apply an OnKeyDown handler to it. The code shown does not work. The context is, I'm trying to capture a short string from the keyboard, which should not include control characters (I've started with the Enter key). Maybe there is a better way?

Thanks!

        public EditText ttsymbol;

/** Called when the activity is first created. */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) { 
        switch (keyCode) { 
        case KeyEvent.KEYCODE_ENTER: 
            // IGNOREenter key!! 
            return true; 

        }return false; 
  }
SirHowy
  • 383
  • 2
  • 6
  • 14

1 Answers1

19

You must bind the onKeyListener to your editText.

myEditText.setOnKeyListener(new OnKeyListener() {           
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction()==KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    //do something here
                    return true;
                }
                return false;
            }
        });
Dyonisos
  • 3,541
  • 2
  • 22
  • 25
  • Thanks, that looks good to me but not to the compiler: Syntax error on token "setonKeyListener" VariableDeclaratorId expected after this token – SirHowy Sep 05 '11 at 09:50
  • Did you instance your edit text with: `ttsymbol = new EditText(context)`? After this you should be able to add the onKeyListener. Just replace "myEditText" with your name e.g. "ttsymbol"! – Dyonisos Sep 05 '11 at 09:59
  • `public EditText ttsymbol= new EditText(getBaseContext()); tsymbol.setOnKeyListener (new OnKeyListener() { ` syntax error on token "setOnKeyListener", = expected after this token – SirHowy Sep 05 '11 at 10:30
  • in your comment you wrote `tsymbol.setOnKeyListener`instead of `ttsymbol.setOnKeyListener` the example I posted works good for me. – Dyonisos Sep 05 '11 at 10:39
  • cut & paste error by me. Doesn't recognise setOnKeyListener as a method of EditText? – SirHowy Sep 05 '11 at 11:02
  • if you want to override the methods fo an own EditText implementation then you have to create a new Class which extends EditText. Otherwise you can instance the EditText in your Activity and add the Listener. – Dyonisos Sep 05 '11 at 11:11
  • 1
    Do remember that this method is only guaranteed to work for hardware keyboards, the software keyboards are not obliged to release these events – Baggers Nov 11 '14 at 09:50
  • above code is not work when is press Device's navigation down key – Mahesh Suthar Apr 02 '16 at 05:28