Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long press Android

Tags:

android

I have problems with detecting long press in my custom view.

Here's the code related to this issue

final GestureDetector gestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        Log.e("dbg_msg", "onLongPress");
    }
});

public boolean onTouchEvent(MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
};

This code detects every single (short) click as long press.

When I put this code in class inherited from Activity, it works.

So why it isn't working in custom View ?

like image 497
Nikola Ninkovic Avatar asked Jul 28 '12 14:07

Nikola Ninkovic


People also ask

What is long press on Android?

Many times, touch & hold lets you take action on something on your screen. For example, to move an app icon on your home screen, touch & hold, then drag it to the new location. Sometimes touch & hold is called a "long press."


1 Answers

All of this code goes in your custom view class:

public static int LONG_PRESS_TIME = 500; // Time in miliseconds 

final Handler _handler = new Handler(); 
Runnable _longPressed = new Runnable() { 
    public void run() {
        Log.i("info","LongPress");
    }   
};

@Override
public boolean onTouchEvent(MotionEvent event) {
    switch(event.getAction()){
    case MotionEvent.ACTION_DOWN:
        _handler.postDelayed(_longPressed, LONG_PRESS_TIME);
        break;
    case MotionEvent.ACTION_MOVE:
        _handler.removeCallbacks(_longPressed);
        break;
    case MotionEvent.ACTION_UP:
        _handler.removeCallbacks(_longPressed);
        break;
    }
    return true;
}
like image 199
Nikola Ninkovic Avatar answered Oct 12 '22 18:10

Nikola Ninkovic