Redman Redman - 1 month ago 13
Android Question

How to have both swipe and touch events for WebView?

Hello guys i am creating epub reader and i have customised my

WebView
to scroll horizontal, now i want to stop the default scroll and do scrolling programatically based on swipe guestures i have already acheive it like this way

public class OnSwipeTouchListener implements OnTouchListener {

private final GestureDetector gestureDetector;

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

public void onSwipeLeft() {
}

public void onSwipeRight() {
}

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

}

private final class GestureListener extends SimpleOnGestureListener {

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

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

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}

}
}


and in my main activity

webView.setOnTouchListener(new OnSwipeTouchListener(this) {
@Override
public void onSwipeLeft() {
// my code to scroll previous page

}

}
@Override
public void onSwipeRight() {
//my code to scroll next page
}
});


now the problem stated, i cannot have the default feature of
WebView
on longpress selecting text, how can i have swiping events and still get the text selection feature on long press?

Answer

By your implementation of onTouch() the onTouchEvent() of the View will not be called, preventing its default touch behaviour to run.

Change the following:

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

To this:

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