Problem with Android's EditText : KeyListener

Joel picture Joel · Jun 29, 2011 · Viewed 23.5k times · Source

On an EditText component, I'm trying to set a KeyListener in order to catch the ENTER key (for form validation).

    text.setKeyListener(new KeyListener() {

        @Override
        public boolean onKeyUp(View view, Editable text, int keyCode, KeyEvent event) {
            return false;
        }

        @Override
        public boolean onKeyOther(View view, Editable text, KeyEvent event) {
            return false;
        }

        @Override
        public boolean onKeyDown(View view, Editable text, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                onKeyEnterPressedListener.onKeyEnterPressed(AKText.this);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public int getInputType() {
            return 1;
        }

        @Override
        public void clearMetaKeyState(View view, Editable content, int states) {

        }
    });

The problem is that whenever I type in the EditText using the keyboard, all the keys are ignored and it's ignoring my keystrokes. However, the softpad on the emulator's device is working.

How to fix this please?

Answer

citizen conn picture citizen conn · Jun 29, 2011

I would use the TextWatcher class instead:

private TextWatcher tw = new TextWatcher() {
    public void afterTextChanged(Editable s){

    }
    public void  beforeTextChanged(CharSequence s, int start, int count, int after){
      // you can check for enter key here
    }
    public void  onTextChanged (CharSequence s, int start, int before,int count) {
    } 
};

EditText et = (EditText) findViewById(R.id.YOUR_EDITTEXT_ID);
et.addTextChangedListener(tw);