同一触摸侦听器被多次调用 [英] Same touch listener is called multiple times

查看:183
本文介绍了同一触摸侦听器被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的屏幕上有多个ImageViews.每当用户将手指移到一个或多个手指上时,我都希望将手指触摸的手指移开并创建新的ImageView.

I have multiple ImageViews on my screen. Whenever the user moves his finger over one or multiple of them, I want the ones the finger touched, to be removed and create new ImageViews.

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    ((ViewGroup) view.getParent()).removeView(view);
    createNewImageViews();
    return true;
}

问题是我的应用程序崩溃了.我认为原因是,再次调用了触摸侦听器,该触摸侦听器已经删除了其视图,并尝试再次将其删除.

The problem is, that my app crashes. I think the reason is, that a touchlistener is called again, that already deleted its view and tries to delete it again.

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.ViewGroup.removeView(android.view.View)' on a null object reference

我应该怎么做才能使其正常工作?

What should I do to make it working properly?

推荐答案

似乎在开始时很困惑:)

It seems you are confused at the start line :)

当Android捕获TouchEvent时,他将他分派到root元素,然后轮到root-以递归方式分派给所有孩子,即认为是视图树,直到某个视图表示已处理touch事件,并且没有人可以处理该事件.

When Android catch TouchEvent, he dispatch him to root element, and root in his turn - dispatch to all childs recursively, thought view tree, until some view signalize that touch event is processed, and no one view can handle this event.

如果您需要将TouchEvent从一个视图分派到另一个视图,则应该跳到一个级别并从那里进行分派.

If you need to dispatch TouchEvent from one View to Another you should jumping up to one level and dispatch from there.

您应该将setOnTouchListener设置为父级ViewGroup,然后扔给他的孩子.

You should set setOnTouchListener to parent ViewGroup and throw forward to his children.

这篇关于同一触摸侦听器被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆