5

I know how to listen for when the ENTER button is pressed in a TextView, as shown in the code below:

textView.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
            if((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                enterPressed();
                return true;
            }
            return false;
        }
});

However... how do I listen for when a character key (A-Z, 0-9, special characters, etc.), basically everything else other than ENTER, BACKSPACE, or SPACE, are pressed? I want to do this because I want a button to become enabled when the user has started typing text into a TextView. Strangely, the onKey() method isn't even called when these character keys are pressed, so is there another way I'm suppose to listen for them? Thanks in advance!

Brian
  • 7,955
  • 16
  • 66
  • 107

3 Answers3

6

Text watcher might help you

textView.addTextChangedListener(new TextWatcher(){

    @Override
    public void afterTextChanged(Editable arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

});
MGK
  • 7,050
  • 6
  • 34
  • 41
1

"Key presses in software keyboards will generally NOT trigger this method, although some may elect to do so in some situations. Do not assume a software input method has to be key-based; even if it is, it may use key presses in a different way than you expect, so there is no way to reliably catch soft input key presses."

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

Xarph
  • 1,429
  • 3
  • 17
  • 26
0

you will have to write a function something like isCharacter(int), Pass the keyCode of the KeyEvent to this function check what is the range of the int - is in the character range which you want for the alphabets and numbers, if so returnTrue in you keypressed function hanlde the case of true or false returned from isCharacter...

iLikeAndroid
  • 1,106
  • 1
  • 8
  • 6
  • Well the main problem is that the method onKey() isn't even called for regular character keys. I tested this by making it write to the log every time a key event was caught. It seems like the onKey() method only gets called for function presses like ENTER or BACKSPACE. – Brian Jun 29 '11 at 04:56
  • Not sure if you have solved this issue... Anyways would like to add this http://stackoverflow.com/questions/1967740/onkeylistener-not-working-with-soft-keyboard-android – iLikeAndroid Aug 01 '11 at 07:09