Reputation: 3293
I'm trying to detect a long press in Android. GestureDetector
is deprecated, so I was trying to use Handler
s. But handler
isn't recognizing postDelayed
or removeCallbacks
. It Cannot resolve method
for either.
final Handler handler = new Handler() {
@Override
public void publish(LogRecord record) {
}
@Override
public void flush() {
}
@Override
public void close() throws SecurityException {
}
};
Runnable longPressed = new Runnable() {
@Override
public void run() {
Log.d("run", "long pressed");
}
};
@Override
public boolean onTouchEvent(MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
handler.postDelayed(longPressed, 500);
break;
case MotionEvent.ACTION_MOVE:
handler.removeCallbacks(longPressed);
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(longPressed);
break;
}
return super.onTouchEvent(event);
}
}
Upvotes: 1
Views: 148
Reputation: 199
You can use Handler if you don't want to use Gesture Detector.
//Declare this flag globally
boolean goneFlag = false;
//Put this into the class
final Handler handler = new Handler();
Runnable mLongPressed = new Runnable() {
public void run() {
goneFlag = true;
//Code for long click
}
};
//onTouch code
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
handler.postDelayed(mLongPressed, 1000);
break;
case MotionEvent.ACTION_UP:
handler.removeCallbacks(mLongPressed);
if(Math.abs(event.getRawX() - initialTouchX) <= 2 && !goneFlag) {
//Code for single click
return false;
}
break;
case MotionEvent.ACTION_MOVE:
handler.removeCallbacks(mLongPressed);
break;
}
return true;
}
Upvotes: 0
Reputation: 19190
GestureDetector is deprecated is not exactly true.
Only the ones Not including Context as constructor parameter are deprecated. Others with context work fine.
final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
public void onLongPress(MotionEvent e) {
Log.e("", "Longpress detected");
}
});
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
};
Upvotes: 0
Reputation: 12866
What about View.OnLongClickListener.html?
You would get something like:
yourView.setOnLongClickListener(new View.OnLongClickListener() {
@Override public boolean onLongClick(View v) {
// Toast it out!
return false;
}
});
Upvotes: 1