17

I need to generate/trigger a long key press event of a button in Android.

Any help regrading this?

Reno
  • 33,594
  • 11
  • 89
  • 102
viv
  • 6,158
  • 6
  • 39
  • 54

2 Answers2

39

From Android 2.0, Activity contains the method

public boolean onKeyLongPress(int keyCode, KeyEvent event)

For exemple, a long key press on the back button would be :

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) 
    {
        // do your stuff here
        return true;
    }
    return super.onKeyLongPress(keyCode, event);
}

Take a look at this article.

William Morrison
  • 10,953
  • 2
  • 31
  • 48
rockeye
  • 2,765
  • 2
  • 30
  • 44
  • You likely need start tracking the event in the onKeyPress handler. See this link: http://stackoverflow.com/questions/5222181/can-you-intercept-the-long-press-on-menu – Craig B Nov 02 '11 at 19:04
  • Why onKeyLongPress() vs. onLongPress()? – IgorGanapolsky May 30 '12 at 17:58
  • Both work but onKeyLongPress is simpler and faster to implement. You can use it directly inside your view. OnLongPress is part of GestureDetector.OnGestureListener. You will have to code the whole gestures detector/listener thing. If you already have one, sure, you can use it. – rockeye May 31 '12 at 08:03
  • Note that onLongKeyPress doesn't work for KEYCODE_BACK, regardless of whether I call event.startTracking() in onKeyDown... – Pierre-Luc Paour Jul 31 '12 at 14:36
  • @Pierre-LucPaour : you have to call startTracking AND return true from onKeyDown as specified in the doc : "_Note that in order to receive this callback, someone in the event change must return true from onKeyDown(int, KeyEvent) and call startTracking() on the event._" – rockeye Jul 31 '12 at 15:23
  • 1
    @rockeye: that's what I'm doing. My onLongKeyPress method isn't getting called (on ICS, with a virtual back key). I noticed that with a physical back key, my views are getting repeating onKey events when I keep pressing on the key, but with a virtual key, I get only a down and an up event, that may explain it. – Pierre-Luc Paour Jul 31 '12 at 15:44
-6

You can set Long key press on button like:

btnNext.setLongClickable(true);
btnNext.setOnLongClickListener(l)
Nishant Shah
  • 3,442
  • 5
  • 25
  • 34
  • Thanks for reply, I think, this will enable long click on button and set a listener for it. What i want is that for example key A(keydown event of a key) is pressed for some time. – viv Aug 04 '10 at 09:11
  • In your listener method before executing any code, put Thread.sleep(2000); It may help you. – Nishant Shah Aug 04 '10 at 10:18