Android 自定义滚动视图出错
我正在为我的水平选择屏幕创建一个“快照到”水平滚动视图。我有一些代码,我不明白为什么它不工作(ScrollView不捕捉,它的行为与正常的ScrollView一样)。滚动视图中可能有一些底层方法需要重写,但我似乎找不到它。以下是我目前的代码:Android 自定义滚动视图出错,android,scrollview,horizontalscrollview,Android,Scrollview,Horizontalscrollview,我正在为我的水平选择屏幕创建一个“快照到”水平滚动视图。我有一些代码,我不明白为什么它不工作(ScrollView不捕捉,它的行为与正常的ScrollView一样)。滚动视图中可能有一些底层方法需要重写,但我似乎找不到它。以下是我目前的代码: public class SnapToScrollView extends HorizontalScrollView implements OnTouchListener { //Marks the point where touch start
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;
}
}
它没有按预期的那样捕捉,它的行为就像一个普通的滚动视图。我也有同样的问题。smoothScrollTo()虽然scrollTo()可以工作,但它什么都不做。我只是把这段代码放到了我的level select屏幕上,我从来没有通过扩展视图编辑来让它工作过:想想看,我甚至认为scrollTo都不起作用。您是否已将SmoothScrolling设置为启用状态?