Scrolller

弹性滑动对象,用于实现View的弹性滑动,我们知道,单纯的使用ScrollTo/ScrollBy其过程是瞬间完成的,这个滑动的过度非常的生硬,那么这个时候可以使用Scroller来实现,Scroller的滑动是在一定的时间之内完成的,Scroller本身是不能使View滑动的,需要借助view的computeScroll来完成

下面贴上Scroller的经典实用模型:

自定义View

public class MyView extends LinearLayout{

    private Scroller mScroller;
   
    public MyView(Context context) {
        super(context);
        mScroller = new Scroller(context);
    }

   
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mScroller = new Scroller(context);

    }

    
    public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mScroller = new Scroller(context);

    }

   
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mScroller = new Scroller(context);
    }


    /**
     * 
     * @param destX  目的x
     * @param destY 目的Y
     */
    public void smoothScrollTo(int destX, int destY) {
        int x = getScrollX();//
        int delta = destX - x;//距离
        mScroller.startScroll(x, 0, delta, 0, 10000);
        invalidate();
    }
    /**
     * Called by a parent to request that a child update its values for mScrollX
     * and mScrollY if necessary. This will typically be done if the child is
     * animating a scroll using a {@link Scroller Scroller}
     * object.
     */
    @Override
    public void computeScroll() {

        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }
}

在自定义View中我们新增了一个Scroller对象,增加了一个方法,参数为滑动的终点坐标,在这里我们只是使这个在X的正方向移动一段距离,然后调用Scroller的startScroll的方法,其实这个startScroll的方法并没有做什么实际的东西

 public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        mMode = SCROLL_MODE;
        mFinished = false;
        mDuration = duration;
        mStartTime = AnimationUtils.currentAnimationTimeMillis();
        mStartX = startX;
        mStartY = startY;
        mFinalX = startX + dx;
        mFinalY = startY + dy;
        mDeltaX = dx;
        mDeltaY = dy;
        mDurationReciprocal = 1.0f / (float) mDuration;
    }
只是将相关的参数保存到Scroller对象中

然后我们重写了View的computeScroll的方法,在里面有一个mScroller.computeScrollOffset()的方法,(贴出会执行的代码)

if (mFinished) {
            return false;
        }

        int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);//当前动画执行的总时间
    
        if (timePassed < mDuration) {//如果比我们设定的时间小,这个动画没有完成
            switch (mMode) {
            case SCROLL_MODE:
		
		//通过时间流失比计算出下一次要到达的坐标
                final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);
                mCurrX = mStartX + Math.round(x * mDeltaX);//这两个值将会在下一步用到
                mCurrY = mStartY + Math.round(x * mDeltaY);
                break;


如果这个函数返回true就说明这个动画没有结束,就是这个view没有滑动到我们设定的坐标

然后就是调用 scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); 来改变这个view的内容的位置,然后重新绘制这个view

在整个的代码中invalidate();是非常重要的(postInvalidate();最终也是调用它),它会导致这个view 重新绘制,然后这个view绘制过程中会调用computeScroll的方法,所以我们才要重写这个方法,

NOTE:这里说的view的滑动都是view的内容滑动,因为使用ScrollTo/ScrollBy

效果:

在来一个郭霖大神blog的一个例子,自己理解了,还是因为粗心写了好多遍

    private static final String TAG = "MyTestView";
    private Scroller mScroller;
    private float xDownPoint;//down 事件的时候x位置
    private float xMoveLastPoint;//上一次move事件x的位置
    private float leftBorder;//左边边界
    private float rightBorder;//右边边界
    private float mTouchSlop;//判断是不是为move事件


    public MyTestView(Context context) {
        super(context);
        initialization(context);
    }

    public MyTestView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialization(context);
    }

    public MyTestView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialization(context);
    }

    private void initialization(Context context) {
        mScroller = new Scroller(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            // 为ScrollerLayout中的每一个子控件测量大小
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (changed) {
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View childView = getChildAt(i);
                // 为ScrollerLayout中的每一个子控件在水平方向上进行布局
                childView.layout(i * childView.getMeasuredWidth(), 0, (i + 1) * childView.getMeasuredWidth(),
                        childView.getMeasuredHeight());
            }
            // 初始化左右边界值
            leftBorder = getChildAt(0).getLeft();
            rightBorder = getChildAt(getChildCount() - 1).getLeft();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                xDownPoint =  ev.getRawX();
                xMoveLastPoint = xDownPoint;
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                float x =  ev.getRawX();
                float distance = Math.abs(x - xDownPoint);
                xMoveLastPoint = x;
                if (distance > mTouchSlop) {
                    return true;
                }

            }
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {


        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE: {

                float x =  event.getRawX();
                //这里为什么不是x - xMoveLastPoint ,因为这里滑动的是他的子view,当你手势从左滑向右的时候,你是想让这个子view向右滑
                //那么你就要是这个父view向左滑,根据坐标,所以就是
                float distance = xMoveLastPoint - x;
                if (distance + getScrollX() < leftBorder) {
                    scrollTo((int) leftBorder, 0);
                    return true;
                }
                if (distance + getScrollX()> rightBorder) {
                    scrollTo((int) rightBorder, 0);
                    return true;
                }
                scrollBy((int) distance, 0);
                xMoveLastPoint = x;
                break;
            }
            case MotionEvent.ACTION_UP: {

                int targetIndex = (getScrollX() + getWidth() / 2) / getWidth();//过一半的时候

                int distance = targetIndex * getWidth() - getScrollX();

                mScroller.startScroll(getScrollX(), 0, distance, 0);
                invalidate();

                break;
            }
        }

        return super.onTouchEvent(event);
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {

            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            invalidate();
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    tools:context="com.example.jinxiong.scroller.MainActivity">

    <com.example.jinxiong.scroller.MyTestView
        android:id="@+id/test"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >

        <Button
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="This is first child view"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="This is second child view"/>

        <Button
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:text="This is third child view"/>


    </com.example.jinxiong.scroller.MyTestView>
</RelativeLayout>

自己理解了才行,然后不要粗心就好敲打























  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值