mercredi 15 juin 2016

Android EditText - Consume event of a specific key press event

I have a class MyEditText that extends EditText. When receiving a specific keycode from an InputMethod service, say 35 which is equivilant of '#', I want to perform an action on my EditText instead of appending it to the text.

Solutions that did not work:

  1. Setting an onEditorActionListener does not help since onEditAction() is called only for a specific set of codes such as KEYCODE_ENTER, and I need to detect the event of receiving a code out of that set.
  2. Setting an onKeyListener. This also did not work but I don't know the reason and I am not even sure this listener is meant for this purpose. This is the code I tried and it never logs anything:

    et.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.d("EDITOR_TAG", "onKey()");
            return false;
        }
    });
    
  3. A workaround that might work but I prefer to avoid: implementing beforeTextChanged(), onTextChanged() and afterTextChanged() of the TextWatcher interface. The reason I want to avoid this is that it will interfere with a history mechanism implemented in those methods (for undo/redo). I want to consume the event of receiving a key code 35 before it even changes the text.

Aucun commentaire:

Enregistrer un commentaire