Reputation: 1262
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 ?
Upvotes: 10
Views: 24945
Reputation: 39
It's better I guess..
public class Workflow extends View implements View.OnLongClickListener {
public Workflow(Context context, DisplayFeatures d) {
super(context);
setLongClickable(true);
setOnLongClickListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
/* onTouchEvent should return super.onTouchEvent(event);, otherwise long click wouldn't be performed */
return super.onTouchEvent(event);
}
@Override
public boolean onLongClick(View v) {
Log.d("VIEW", "LONG CLICK PERFORMED!");
return false;
}
}
Upvotes: 0
Reputation: 1262
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;
}
Upvotes: 25
Reputation: 199
I'm not sure but your GestureDetector
's constructor is deprecated (here). Could you try other ones which need a context as first parameter?
Sorry I'm new so I can't post comment.
— Edited —
It seems you used another listener, this View.OnTouchListener
has other onTouch()
method. Could you try again?
— Edited —
Here is an example (worked for me):
...
mAnotherView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return mGestureDetector.onTouchEvent(event);
}
});
...
mGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
@Override
public void onLongPress(MotionEvent e) {
// do your tasks here
}
});
Upvotes: 4
Reputation: 1193
Did you enable long presses on your GestureDetector? You can enable it either using an appropriate constructor, or by calling setIsLongpressEnabled. For instance, you can do:
gestureDetector.setIsLongpressEnabled(true);
in your constructor.
Upvotes: 4