I\'m trying to create a layout with a ViewFlipper containing ScrollViews. The idea is to detect horizontal swipes to move to previous/next ScrollView. Moreover, the ScrollVi
I had to add
@Override
public boolean dispatchTouchEvent(MotionEvent ev){
super.dispatchTouchEvent(ev);
return productGestureDetector.onTouchEvent(ev);
}
in my Activity.
parentScrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return productGestureDetector.onTouchEvent(event);
}
});
set your main scrollview on TouchListener and implement this code this work for me. I hop to will be helpful for you.
My answer is the same as my last one except I'm going to be more explicit.
Change
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:background="@color/grey_bg">
to
<your.packagename.CustomScrollView ... etc>
Create a class
public class CustomScrollView extends ScrollView {
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
gestureDetector = new GestureDetector(new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
return super.onTouchEvent(ev);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
//Call super first because it does some hidden motion event handling
boolean result = super.onInterceptTouchEvent(ev);
//Now see if we are scrolling vertically with the custom gesture detector
if (gestureDetector.onTouchEvent(ev)) {
return result;
}
//If not scrolling vertically (more y than x), don't hijack the event.
else {
return false;
}
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
try {
if (Math.abs(distanceY) > Math.abs(distanceX)) {
return true;
} else {
return false;
}
} catch (Exception e) {
// nothing
}
return false;
}
}
That code comes from the top answer here: HorizontalScrollView within ScrollView Touch Handling (So go give it a vote up if the answer is useful).
If you want to get the perpendicular direction then change
if (Math.abs(distanceY) > Math.abs(distanceX)) {
to
if (Math.abs(distanceY) < Math.abs(distanceX)) {
The CustomScrollView
will only intercept swipes in one axis, either horizontally or vertically depending the 2 lines of code above. Since it only intercepts swipes in one axis the rest of the events will be passed to its children, now you can handle the event with your gesture/touch listener in your activity.
You will also need to change any references/casts to ScrollView
to the new custom one (CustomScrollView
).