0
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int action = event.getAction();
    int keyCode = event.getKeyCode();

        switch (keyCode) {
        case KeyEvent.KEYCODE_VOLUME_UP:
            if (action == KeyEvent.ACTION_UP) {
                //navigate up
            }

            return true;

        case KeyEvent.KEYCODE_VOLUME_DOWN:
            if (action == KeyEvent.ACTION_DOWN) {
                //navigate down
               }
            return true;
        default:
            return super.dispatchKeyEvent(event);
       }


    }

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
       startActivity(new Intent(getApplicationContext(), fish.class));
       return true;
    }

    return super.onKeyLongPress(keyCode, event);
}

I have few buttons in a class which i want to navigate using the volume up/down keys. and want to press the button when the key is long pressed. The navigation through the buttons works perfectly fine but the long press to click the button in the class doesn't works.

Deb
  • 33
  • 5

1 Answers1

1

Use

public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
       startActivity(new Intent(getApplicationContext(), FISH.class));
       return true;
    }

    return super.onKeyLongPress(keyCode, event);
}

provided you have FISH class extending Activity.

Melquiades
  • 8,496
  • 1
  • 31
  • 46
  • Tried it. It doesn't works. I have a menu activity class which has few buttons. For navigation i want to use the volume buttons. The short key press works fine to navigate through the various buttons and i want to click the button when a long keypress happens. – Deb Dec 30 '13 at 18:58
  • Sure, check this: http://stackoverflow.com/questions/12950215/onkeydown-and-onkeylongpress?lq=1 – Melquiades Dec 30 '13 at 19:00
  • Have tried this link also. Nothing comes up on the Logcat. I am using public boolean dispatchKeyEvent(KeyEvent event) for detecting the short key press for the navigation between various buttons. – Deb Dec 30 '13 at 19:02
  • Ok, what exactly are you trying to do? One thing on long press? Another on short press? Please update your post with the rest of your code and more details. Also, `unable to do so` - what does it mean exactly? – Melquiades Dec 30 '13 at 19:08
  • For what it seems, the code under the link provided could be adjusted to suit your needs. Use onKeyLongPress, onKeyDown and onKeyUp together with a flag. – Melquiades Dec 30 '13 at 19:23