jjNford
jjNford

Reputation: 5270

How can I create a long touch event on the physical menu button?

Right now when you hold down the menu button on my android device it pulls up a soft keyboard.Is there a way to override this? I would rather choose what happens on a long touch of this button.

When using onKeyLongPress it only detects when the "Back" button is held down. How can I make this work for the menu button?

Upvotes: 1

Views: 1387

Answers (1)

Lukas Knuth
Lukas Knuth

Reputation: 25755

For this, you can use the onKeyLongPress()-method, offered by the KeyEvent.Callback-class (can be used in Activity's too, since they are a subclass of the KeyEvent.Callback-class).

There is also a little trick to make this work: You'll have to tell Android to track a long-press click on the "Menu"-button as the onKeyLongPress()-method will not be triggered otherwise. This is done in the normal onKeyDown()-method.

So your code might look like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        // this tells the framework to start tracking for
        // a long press and eventual key up.  it will only
        // do so if this is the first down (not a repeat).
        event.startTracking();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event){
    if (keyCode == KeyEvent.KEYCODE_MENU){
        // Do what you want...
        Toast.makeText(this, "I'm down!", Toast.LENGTH_SHORT).show();
        return true;
    }
    return super.onKeyLongPress(keyCode,event);
}

A great article with further informations can be found on the Android Developer Blog.

Upvotes: 2

Related Questions