11

So I have my activity which has a main ViewPager and inside of the ViewPager each page has the whole content as a ScrollView and inside of that ScrollView there is another ViewPager.

This might sound crazy but basically the outer ViewPager contains news articles, and the articles are long so there is a ScrollView, and inside the ScrollView there are multiple thumbnails/pictures that they can swipe through as well.

I've tried a few different custom ViewPagers with different touch event interception but can't seem to get it perfect. It either completely will absorb all touch events so that the vertical scrolling of the ScrollView doesn't work in that area, or it will be really touchy/difficult to get the inner one to scroll horizontally.

Anyone have a perfect solution?

4

1 回答 1

12

如果有人想知道我的解决方案:

public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
View.OnTouchListener mGestureListener;

public CustomScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
    mGestureDetector = new GestureDetector(context, new YScrollDetector());
    setFadingEdgeLength(0);
}

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    return super.onInterceptTouchEvent(ev)
            && mGestureDetector.onTouchEvent(ev);
}

// 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) {
        if (Math.abs(distanceY) > Math.abs(distanceX)) {
            return true;
        }
        return false;
    }
}
}

最外面的 ViewPager 是:

public class NestingViewPager extends ViewPager {

public NestingViewPager(final Context context, final AttributeSet attrs) {
    super(context, attrs);
}

public NestingViewPager(final Context context) {
    super(context);
}

@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
    if (v != this && v instanceof ViewPager) {
        return true;
    }
    return super.canScroll(v, checkV, dx, x, y);
}
}
于 2013-06-12T15:25:02.323 回答