My first idea was to use the onTouchEvent(MotionEvent event) callback.
The only thing I have to do is to capture the time at the MotionEvent.ACTION_DOWN event and calculate the time difference inbetween an other event. Is it bigger than lets say 1 second it is a long click.
But what could be the next event? ACTION_UP comes whenever. And ACTION_MOVE indicates a gesture like drag but not a long click.
Do I have to implement a Thread?
The answer is realy easy. There is an official event for the job. You can register the View.OnLongClickListener to every View.
The listener gets either called by a user touch or you can call it programmatically with the performeLongClick() method.
Here comes an example that registers the listener on a button and sets a string into a TextView to have a visual feedback.
button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
textView.setText("long clicked");
return true;
}
});
Caution!
There are two things to keep in mind.
1. If you like me developing a custom view you probably override the onTouchEvent() methode.
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
return super.onTouchEvent(event);
}
Don't remove the super.onTouchEvent(event) regardless what you return. It triggers the whole event processing of the parent view. If you leave it out the onLongClick event will never occur. 2. If you return true with the onLongClick(View v) method you tell the view the click is handled and a registered ContextMenu won't come um.
No comments:
Post a Comment