我扩展了HorizontalScrollView
类来实现某种行为。在CustomHorizontalScrollView
内的LinearLayout下,我只有2个子视图(比如ImageView
)。当用户向一个方向滚动超过50%时,我希望我的CustomHorizontalScrollView
自动滚动到同一方向的末尾。这就是我实施它的方式:
CustomHorizontalScrollView
课程:
public class CustomHorizontalScrollView extends HorizontalScrollView {
private static float downCoordinates = -1;
private static float upCoordinates = -1;
private static int currentPosition = 0;
public CustomHorizontalScrollView(Context ctx) {
super(ctx);
}
public CustomHorizontalScrollView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN && downCoordinates == -1) {
downCoordinates = ev.getX();
}
else if (ev.getAction() == MotionEvent.ACTION_UP && upCoordinates == -1) {
upCoordinates = ev.getX();
int scrollViewWidth = this.getMeasuredWidth();
double dist = downCoordinates - upCoordinates;
if (Math.abs(dist) > scrollViewWidth / 2) {
//this.setSmoothScrollingEnabled(true);
// Going forwards
if (dist > 0) {
int max = ((LinearLayout)this.getChildAt(0)).getChildAt(1).getMeasuredWidth();
currentPosition = max;
this.scrollTo(max, 0);
}
// Going backwards
else {
currentPosition = 0;
this.scrollTo(0, 0);
}
}
// reseting the saved Coordinates
downCoordinates = -1;
upCoordinates = -1;
}
return super.onTouchEvent(ev);
}
}
直到这里 - 一切正常。问题是我希望自动滚动顺利完成所以我尝试使用smoothScrollTo
函数而不是scrollTo
函数,但是没有任何反应(如没有自动滚动)。我试着宣布这个:
this.setSmoothScrollingEnabled(true);
但也没有成功。
答案 0 :(得分:12)
你试过这个吗?
this.post(new Runnable() {
public void run() {
this.smoothScrollTo(0, this.getBottom());
}
});
答案 1 :(得分:1)
这仍然不适合我,所以我发现我需要在这一行之后
this.smoothScrollTo(0, this.getBottom());
添加此
this.invalidate();