Anindya Basu Anindya Basu - 2 months ago 15
Android Question

onKey onKeyDown not working

I'm trying to register directional pad / tv remote d pad clicks in my android app. I'm currently testing with the android emulator and I'm trying to click with the directional pad input under the extra settings menu. But I'm not sure why this doesn't work - any help would be appreciated

public class FullscreenActivity extends AppCompatActivity {

private View mContentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);

mContentView = findViewById(R.id.fullscreen_content);

mContentView.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d("debug", "we are here");
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
Log.d("keycode", "center pressed");
return true;
}
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
case KeyEvent.KEYCODE_DPAD_DOWN:
case KeyEvent.KEYCODE_DPAD_RIGHT:
case KeyEvent.KEYCODE_DPAD_LEFT:
case KeyEvent.KEYCODE_DPAD_CENTER:
Log.d("OnKey", "key pressed!");
return true;
}
return false;
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return super.onKeyDown(keyCode, event);
}
}


running this code gives me no output whatsoever on logcat

Answer

You can override onKeyDown() method of your activity to detect key press.

Try this

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (event.getAction() == KeyEvent.ACTION_DOWN) {

        switch (event.getKeyCode()) {
            case  KeyEvent.KEYCODE_DPAD_UP:
                 showToast("UP pressed");
            return true;
            case  KeyEvent.KEYCODE_DPAD_DOWN:
                 showToast("DOWN pressed");
            return true;
            case  KeyEvent.KEYCODE_DPAD_RIGHT:
                 showToast("RIGHT pressed");
            return true;
            case  KeyEvent.KEYCODE_DPAD_LEFT:
                 showToast("LEFT pressed");
            return true;
            case  KeyEvent.KEYCODE_DPAD_CENTER:
                 showToast("CENTER pressed");
            return true;
           }
         }
        return super.onKeyDown(keyCode, event);
  }

  void showToast(String msg)
  {
    Toast.makeText(getApplicationContext(),msg,Toast.LENGTH_SHORT).show();
  } 
Comments