自定义ScrollView出错

时间:2013-03-27 15:55:53

标签: android scrollview horizontalscrollview

我正在为我的关卡选择屏幕创建一个'snap to'FineralScrollView。我有一些代码,我无法理解为什么它不起作用(ScrollView不会捕捉,它表现为普通的ScrollView)。滚动视图中可能有一些底层方法需要覆盖,但我似乎无法找到它。到目前为止,这是我的代码:

public class SnapToScrollView extends HorizontalScrollView implements
    OnTouchListener {

//Marks the point where touch starts
float pointDown;
//Marks the position of the ScrollView when touch first occurs, used to snap
float startX;

public SnapToScrollView(Context context) {
    super(context);
    setSmoothScrollingEnabled(true);
}

public SnapToScrollView(Context context, AttributeSet attrs) {
    super(context, attrs);
    setSmoothScrollingEnabled(true);
}

public SnapToScrollView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    setSmoothScrollingEnabled(true);
}

@Override
public boolean onTouch(View v, MotionEvent event) {
    //If motion is stopped, then snap to nearest
    if (event.getAction() == MotionEvent.ACTION_UP) {
        //determine if we have moved far enough from original touch
        if (Math.abs(pointDown - event.getX()) > 640) {
            //Move backwards or forwards
            int c = (int) ((pointDown - event.getX()) / Math.abs(pointDown
                    - event.getX()));
            smoothScrollTo((int) (startX + c * 640), 0);
        } //else scroll to where we started
        else {
            smoothScrollTo((int) startX, 0);
        }
    } // when first touch happens, record coordinates
    else if (event.getAction() == MotionEvent.ACTION_DOWN) {
        startX = getScrollX();
        pointDown = event.getX();
    } // If it is not first or last touch, then scroll
    else {
        smoothScrollTo((int) (startX + event.getX()), 0);
    }
    return true;
}
}

0 个答案:

没有答案