2

I have a simple code that shows strings in a TextView after a button is pressed or when the user press 'Enter'. When the user presses the button all is find, but when the 'enter' is pressed, it calls performClick() to call the same function than the button does. But my fonction is always called twice :

 private OnKeyListener ChampKeyListener = new OnKeyListener()
    {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if(keyCode == KeyEvent.KEYCODE_ENTER)
            {
                recherche.performClick(); // recherche is my button
            }
            return false;
        }
    };

    private OnClickListener RechercheListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
        //whatever I have tried here it is always called twice

        }
    };

How can I stop that. I have seen that I could solve that my going to another View or Activity but I don't want to use those.

Any hint? Thanks!

castors33
  • 477
  • 10
  • 26

2 Answers2

6
  1. As there are two actions on press KeyEvent.ACTION_DOWN & KeyEvent.ACTION_UP

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

Returns true if the listener has consumed the event, false otherwise.

Try it...

public boolean onKey(View v, int keyCode, KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN)
          {
                if(keyCode == KeyEvent.KEYCODE_ENTER)
                {
                    recherche.performClick(); // recherche is my button
                    return true;
                }


           }

    return false;
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
  • or better to use this http://stackoverflow.com/questions/4451374/use-enter-key-on-softkeyboard-instead-of-clicking-button/4451825#4451825 to hanlde KEYCODE_DPAD_CENTER as well – Dheeresh Singh Jun 29 '12 at 20:22
  • Thanks that solves my problem! And the other tread was useful too! – castors33 Jul 03 '12 at 13:13
2

It could be that the event is fired twice, once when the key is pressed and again when it is released. Try:

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_ENTER &&
            event.getAction() == KeyEvent.ACTION_DOWN) {
        recherche.performClick(); // recherche is my button
        return true; // consume event
    }
    return false;
}
Jeshurun
  • 22,940
  • 6
  • 79
  • 92