Why is onKey() called twice?
Solution 1:
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;
}
});
Solution 2:
itemView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
int pos = getAdapterPosition();
if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_MENU){
//code here
}
return false;
}
});