view_的滑动

View 的滑动

1.使用Scroller

    Scroller mScroller=new Scroller(context);

    public void smoothScrollTo(int destX, int destY) {
         Log.w(TAG,"before smoothScroll-----------scrollX="+getScrollX());
         int scrollX = getScrollX();
         int deltaX = destX - scrollX;
         int scrollY = getScrollY();
         int deltaY = destY - scrollY;
         mScroller.startScroll(scrollX,scrollY,deltaX,deltaY,1000);
         invalidate();
    }

    @Override
    public void computeScroll() {
        if(mScroller.computeScrollOffset()){
            scrollTo(mScroller.getCurrX(),mScroller.getCurrX());
            Log.w(TAG,"after smoothScroll-----------scrollX="+getScrollX());
            postInvalidate();
        }
    }
  • getScrollX()、getScrollY()的值为滑动起始坐标,当滑动完成后,该值就会更新为滑动之后的坐标。

  • startScroll(sx,sy,dx,dy,ti)函数并不会执行滑动,而是纪录滑动的参数,sx、sy为滑动起始位置,dx、dy为滑动距离,ti为滑动时间(ms)。

    startScroll()的源码:
    
    
    /**Start scrolling by providing a starting point, the distance to travel,
    * and the duration of the scroll.
    *
    * @param startX Starting horizontal scroll offset in pixels. Positive
    *        numbers will scroll the content to the left.
    * @param startY Starting vertical scroll offset in pixels. Positive numbers
    *        will scroll the content up.
    * @param dx Horizontal distance to travel. Positive numbers will scroll the
    *        content to the left.
    * @param dy Vertical distance to travel. Positive numbers will scroll the
    *        content up.
    * @param duration Duration of the scroll in milliseconds.
    */
    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;
    }  
    
  • computeScroll()

    在computeScroll()中,先使用computeScrolloffset()方法进行判断当前滑动事件是否完成,若未完成,则继续调用scrollTo()直到滑动到指定的地点,postInvalidate是执行Draw重绘操作。

2.使用动画

ObjectAnimator.ofFloat(targetView,"translateX",0,100).setDuration(100).start()

猜你喜欢

转载自blog.csdn.net/u013648164/article/details/52498233
今日推荐