在Gallery中的ScrollView,都可以独立滚动

时间:2011-03-12 22:55:26

标签: android user-interface touch scrollview android-gallery

我有一个带适配器的Gallery,它为ScrollViews提供子视图。 我需要确保按预期正确处理触摸事件:

  1. 当用户水平滚动时,图库会水平滚动。
  2. 当用户垂直滚动时,滚动视图会垂直滚动。
  3. 两个卷轴都不应该出现在同一个手势上(用户必须抬起手指才能滚动另一个手势)。
  4. 一切都必须顺利滚动。
  5. 如果没有覆盖任何方法,滚动视图是滚动的唯一内容 - 图库永远不会滚动。

    所以我理解我需要在库中使用onInterceptTouchEvent(...)来决定接管一系列的MotionEvent,但我不确定如何检查触摸是否是水平或垂直的。

2 个答案:

答案 0 :(得分:19)

好的,经过一些重大的摆弄和logcat黑客攻击,这是解决方案:

public class SwipeInterceptingGallery extends Gallery {

    private float mInitialX;
    private float mInitialY;
    private boolean mNeedToRebase;
    private boolean mIgnore;

    public SwipeInterceptingGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public SwipeInterceptingGallery(Context context) {
        super(context);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
            float distanceY) {
        if (mNeedToRebase) {
            mNeedToRebase = false;
            distanceX = 0;
        }
        return super.onScroll(e1, e2, distanceX, distanceY);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                mIgnore = false;
                mNeedToRebase = true;
                mInitialX = e.getX();
                mInitialY = e.getY();
                return false;
            }

            case MotionEvent.ACTION_MOVE: {
                if (!mIgnore) {
                    float deltaX = Math.abs(e.getX() - mInitialX);
                    float deltaY = Math.abs(e.getY() - mInitialY);
                    mIgnore = deltaX < deltaY;
                    return !mIgnore;
                }
                return false;
            }
            default: {
                return super.onInterceptTouchEvent(e);
            }
        }
    }
}

答案 1 :(得分:0)

我尝试过Warlax提供的解决方案。它让我前进,但不幸的是,它在一些罕见的情况下打破了正常的画廊行为。 (例如,滚动时不会停止触摸)所以我做了更多的研究,并提出了以下解决方案。

public class TouchInterceptingGallery extends Gallery {

    public TouchInterceptingGallery(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    public TouchInterceptingGallery(Context context) {
        super(context);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        this.onTouchEvent(ev);
        return false;
    }

}
相关问题