Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is onKey() called twice?

Tags:

android

I am using this code:

public boolean onKey(View v, int keyCode, KeyEvent event) { msg = (EditText)findViewById(R.id.msg); String message = msg.getText().toString();             if(keyCode == 66)             {                 //It's hitting here twice.                       }             return false;         }; 

Can anyone please tell me why it's hitting twice when I press enter?

like image 922
SPB Avatar asked Sep 27 '10 10:09

SPB


1 Answers

OnKey is fired twice: the first time for key down, and the second time for key up, so you have to filter:

YOUR_VIEW.setOnKeyListener(new OnKeyListener()         {                                        @Override             public boolean onKey(View v, int keyCode, KeyEvent event) {                  //This is the filter                 if (event.getAction()!=KeyEvent.ACTION_DOWN)                     return true;                  switch (keyCode) {                 case KeyEvent.KEYCODE_1 :                      MakeToast(1);                     break;                 case KeyEvent.KEYCODE_2 :                      MakeToast(2);                     break;                 case KeyEvent.KEYCODE_3 :                      MakeToast(3);                     break;                  }                  return true;             }          }); 
like image 75
Redax Avatar answered Sep 18 '22 01:09

Redax