CustomHorizontalScrollView

CustomHorizontalScrollView

我扩展了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);


但也没有成功。

最佳答案

你有尝试过吗?

    this.post(new Runnable() {
        public void run() {
             this.smoothScrollTo(0, this.getBottom());
        }
});

07-27 13:45