简体   繁体   中英

Android getting ACTION_UP without ACTION_DOWN

Hi i want to pass the touch event to the parent, only if the touch has moved, when the user clicks i want to handle it within the child, so i tried this within the child:

private boolean moved = false;
@Override
public boolean onTouchEvent(MotionEvent event)
{
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        super.onTouchEvent(event);
        moved = false;
        return false;
    }
    if (event.getAction() == MotionEvent.ACTION_MOVE) {
        moved = true;
        return false;
    }
    if (event.getAction() == MotionEvent.ACTION_UP) {
        return !moved;
    }
    return true;
}

but when i return false on ACTION_DOWN i do not get ACTION_UP

On the time ACTION_DOWN occours i do not know if i will handle it or not

"If you return true from an ACTION_DOWN event you are interested in the rest of the events in that gesture. A "gesture" in this case means all events until the final ACTION_UP or ACTION_CANCEL. Returning false from an ACTION_DOWN means you do not want the event and other views will have the opportunity to handle it. If you have overlapping views this can be a sibling view. If not it will bubble up to the parent." - What is meaning of boolean value returned from an event-handling method in Android

When you return false you don't consume touch event and it is passed to the parent (and as you've found out by experiment you can't proceed on that gesture), if you return true - you take responsibility of processing.

So try this

    private boolean moved = false;
    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // CALL YOUR PARENT onTouch() IF YOU NEED TO
            moved = false;
        }

        else if (event.getAction() == MotionEvent.ACTION_MOVE)
            moved = true;

        else if (event.getAction() == MotionEvent.ACTION_UP)
            return !moved;

        return true;
    }

According to this official Android developer site link (Read Capturing touch events for a single view section)

Beware of creating a listener that returns false for the ACTION_DOWN event. If you do this, the listener will not be called for the subsequent ACTION_MOVE and ACTION_UP string of events. This is because ACTION_DOWN is the starting point for all touch events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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