Same touch listener is called multiple times

隐身守侯 提交于 2019-12-11 07:32:44

问题


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?


回答1:


It seems you are confused at the start line :)

Some explanation.

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.

So.

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

Diagram

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



来源:https://stackoverflow.com/questions/38168601/same-touch-listener-is-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!