How To Detect When Any Child View Recieves A Click
Solution 1:
Here is how I do it:
//in onTouch method of parent, I get the coordinates of clickintx= ((int) motionEvent.getX());
inty= ((int) motionEvent.getY());
//obtain the clickable arrea of the child as HitRectRectclickRect=newRect();
Rectrect=newRect();
imageView.getHitRect(rect);
//ask if the area contains the coordinates of the clickif(rect.contains(x, y)){
//do some work like if onClickListener on the child was called.returnfalse; //you clicked here, don't need to handle other Childs
}
//ask for other childs like before...
Now, you can target the parent as the delegate of all clicks done inside it, even if it is done in a child.
EDIT:
To ignore other touch event that are not click, you can ask for how much user moved the finger:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
returntrue; // user mover finger too much, ignore touch
}
returnfalse; // finger still there waiting for click
I give a square of 10 pixels to permit a confortable click, and if you exit it, I ignore it.
EXTRA:
Here is the complete code for click and long click with onTouchListener.
Solution 2:
You could use the View.getChildCount() to loop through all child views and see if the touch intersects with the child view. This involves getting x and y positions and calculating if it fits within the child view, use View.getChildAt(position) to get the reference to the child view .
So it would be something like this:
intchildNr= theView.getChildCount();
for (inti=0; i < childNr; i++){
YourViewtmp= (YourView) theView.getChildAt(i);
if(tmp.intersects(x, y)){
do some work
}
}
here you would have to put your view variable instead of theView and the class name which handles the views instead of (YourView) and x, y are the coordinates of the pressed spot.
Solution 3:
In your XML, you could add point all the children to the same onClick method. Inside that method you could draw the highlight to G and then do something (or nothing) for the individual child view.
Post a Comment for "How To Detect When Any Child View Recieves A Click"