Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Android's EditText : KeyListener

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?

like image 682
Joel Avatar asked Jun 29 '11 00:06

Joel


2 Answers

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);
like image 178
citizen conn Avatar answered Nov 03 '22 00:11

citizen conn


Did you mean to use setOnKeyListener()?

http://developer.android.com/reference/android/view/View.html#setOnKeyListener(android.view.View.OnKeyListener)

http://developer.android.com/reference/android/view/View.OnKeyListener.html

editText.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Log.i("KEY", Integer.toString(keyCode));
        return false;
    }
});
like image 42
Dan Dar3 Avatar answered Nov 03 '22 01:11

Dan Dar3