Same touch listener is called multiple times

2019-07-30 14:08发布

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条回答
在下西门庆
2楼-- · 2019-07-30 15:01

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

enter image description here

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

查看更多
登录 后发表回答