简体   繁体   English

尝试在自定义视图的onTouchEvent中检测子视图

[英]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. 除了一件事,我已完成所有工作,当手指穿过一颗星星时,星星必须变红并发出噪音。

在此处输入图片说明

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. 我的自定义视图是一个从RelativeLayout扩展的类,其中有一些ImageView ,它们是星星。 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. 要添加星星,我只是从数据结构中读取有关人​​物的数据,然后即时实例化ImageView ,为它们添加适当的边距以制作人物。 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 . 到目前为止,我已经尝试使用setOnTouchListener中每颗恒星,覆盖onTouchEvent从星星的意见,使用setOnTouchListeneronTouchEventsetOnHoverListenersetOnDragListenerRelativeLayout 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 . 其中vStarsCollection是我在RelativeLayout添加的ImageView的集合。 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? 我怎样才能做到这一点?

Instead of adding the touch listener to each star, try adding to your custom view (ie, relativelayout). 与其将触摸侦听器添加到每个星星,不如尝试添加到您的自定义视图(即,relativelayout)。

Then in the onTouch callback, add your existing logic to change the color. 然后在onTouch回调中,添加现有逻辑以更改颜色。

So that onTouch will not go out of your view bounds 这样onTouch不会超出您的视野范围

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM