0

我正在为我的关卡选择屏幕创建一个“对齐”Horizo​​ntalScrollView。我有一些我不明白为什么它不起作用的代码(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;
}
}
4

0 回答 0