问题
I have implemented a custom TextView
class so that I can handle touch and touch release events for TextView
s that exist in a GridView
. I got that to work well. However, I also had set up OnItemClickListener
for the GridView
so I can handle that event and run code in the main fragment - on click wouldn't be appropriate to handle in the custom TextView
class itself. But now that I have implemented both of those they are conflicting and the event to release the touch is not being triggered now.
How do I allow these gesture events to both be triggered - onTouchEvent
in a custom class and OnItemClickListener
in the GridView, without losing some of the action events?
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//handle click
}
});
In the custom TextView class:
@Override
public boolean onTouchEvent(MotionEvent event) {
//handle touch and release events only
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//handle touch down
}
else if (event.getAction() == MotionEvent.ACTION_UP
|| event.getAction() == MotionEvent.ACTION_MOVE
|| event.getAction() == MotionEvent.ACTION_CANCEL
|| event.getAction() == MotionEvent.ACTION_OUTSIDE
|| event.getAction() == MotionEvent.ACTION_SCROLL) {
//handle touch release
}
return super.onTouchEvent(event);
}
With this code, when I tap and release a TextView
, the touch down code is run, the OnItemClickListener
is called in the GridView
, but onTouchEvent
is not called again so the touch release event is not handled.
If I change onTouchEvent
to the following, the touch and touch release is properly handled but OnItemClickListener
is not called:
super.onTouchEvent(event);
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//handle touch down
return true;
} else if (event.getAction() == MotionEvent.ACTION_UP
|| event.getAction() == MotionEvent.ACTION_CANCEL
|| event.getAction() == MotionEvent.ACTION_OUTSIDE
|| event.getAction() == MotionEvent.ACTION_SCROLL) {
//handle touch release
return false;
}
return true;
来源:https://stackoverflow.com/questions/27083249/making-ontouchevent-play-nice-with-onitemclicklistener