Same touch listener is called multiple times

2019-07-30 14:55发布

问题:

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.