Search code examples
androidandroid-relativelayoutgesture

Trying to detect child views in the onTouchEvent in a custom view


I'm trying to make a game for kids, in this game you have figures made with some stars, the kid must connect the stars using the finger. I've everything done except for one thing, when the finger comes through one of the stars, the star must turn red and make a noise.

enter image description here

The star does turn red a make a noise, but only if I make tap on them. If I try to drag the finger through the figure, only the first star where I did tap will ring and turn red, the rest will not. My custom view is a class that extends from RelativeLayout wich have some ImageView's in there, that are the stars. To add the stars I just read the data about the figure from a data structure and I instantiate the ImageView's on the fly, adding them the proper margin to make the figure. So far I've tried use the setOnTouchListener in each star, override the onTouchEvent from the stars views, use the setOnTouchListener, onTouchEvent, setOnHoverListener and setOnDragListener in the RelativeLayout. In each of this methods the way that I've implemented to check the views in the callback is by doing:

            for (View v : vStarsCollection) {
                Rect viewBounds = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
                if (viewBounds.contains((int)event.getX(), (int)event.getY())) {
                    MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.right_simon_sound);
                    mp.start();
                    ((ImageView) v).setImageResource(R.drawable.star_red);
                }
            }

Where vStarsCollection is a collection of the ImageView that I added in the RelativeLayout. Like I told you, the code works when I do tap, but doesnt when I drag the finger across the stars. How can I do this?


Solution

  • Instead of adding the touch listener to each star, try adding to your custom view (i.e., relativelayout).

    Then in the onTouch callback, add your existing logic to change the color.

    So that onTouch will not go out of your view bounds