Droidman
Droidman

Reputation: 11608

how to prevent a View from being "pressed" on touch event

I have a RecyclerView with my own implementation of an OnItemClickListener. To highlight the clicked item, I use a simple selector as its background:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/item_inner_rect_pressed" android:state_pressed="true" />
<item android:drawable="@drawable/item_inner_rect" />
 </selector>

The problem: since I also use an OnTouchListener to detect left-to-right swipe gestures, the list item becomes "pressed" when a swipe gesture is performed, though no click event did occur. As a result, the "pressed" state drawable gets set.

Any ideas how to avoid that?

EDIT: my Touch listener looks like this (adapted from some other solutions here on SO):

public class OnSwipeTouchListener implements View.OnTouchListener {

private final GestureDetector gestureDetector;

public OnSwipeTouchListener(Context context) {
    gestureDetector = new GestureDetector(context, new GestureListener());
}

//not needed
public void onSwipeLeft() {
}

public void onSwipeRight() {
}

public boolean onTouch(View v, MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

    private static final int SWIPE_DISTANCE_THRESHOLD = 100;
    private static final int SWIPE_VELOCITY_THRESHOLD = 100;
    private static final int XY_VELOCITY_DIFFERENCE_THRESHOLD = 200;

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        if (e1 == null || e2 == null)
            return false;

        float distanceX = e2.getX() - e1.getX();
        float distanceY = e2.getY() - e1.getY();
        if (Math.abs(distanceX) > Math.abs(distanceY)
                && (Math.abs(velocityX) - Math.abs(velocityY) > XY_VELOCITY_DIFFERENCE_THRESHOLD)
                && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD
                && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
            if (distanceX > 0)
                onSwipeRight();
            else
                onSwipeLeft();
            return true;
        }
        return false;
    }
 }
}

EDIT #2: I suppose that I somehow need to figure out when exactly a View becomes "pressed" (through not "clicked") to get a starting point. Any ideas are appreciated.

Upvotes: 0

Views: 941

Answers (1)

RogueBaneling
RogueBaneling

Reputation: 4471

In the onTouch() method, return false. This will tell Android that the OnTouchListener is not responsible for handling the gesture.

Upvotes: 2

Related Questions