package com.liuyang.code.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Scroller;
import android.widget.TextView;

/**
 * @author Liuyang 2016/3/23.
 */
public class ScrollerView extends TextView {
    private Scroller mScroller;

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

    //调用此方法滚动到目标位置
    public void smoothScrollTo(int fx, int fy) {
        int dx = fx - mScroller.getFinalX();
        int dy = fy - mScroller.getFinalY();
        smoothScrollBy(dx, dy);
    }

    //调用此方法设置滚动的相对偏移
    public void smoothScrollBy(int dx, int dy) {
        //设置mScroller的滚动偏移量
        mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx, dy);
        invalidate();//这里必须调用invalidate()才能保证computeScroll()会被调用，否则不一定会刷新界面，看不到滚动效果
    }

    @Override
    public void computeScroll() {
        //先判断mScroller滚动是否完成
        if (mScroller.computeScrollOffset()) {
            //这里调用View的scrollTo()完成实际的滚动
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            //必须调用该方法，否则不一定能看到滚动效果
            postInvalidate();
        }
        super.computeScroll();
    }
}

@@ -94,16 +94,49 @@
 uteSet;%0A
+import android.view.MotionEvent;%0A
 import a
@@ -306,16 +306,64 @@
 croller;
+%0A    private int mLastX;%0A    private int mLastY;
 %0A%0A    pu
@@ -1313,11 +1313,694 @@
 );%0A    %7D
+%0A%0A    // uncomment this part to make this view move with the finger.%0A    @Override%0A    public boolean onTouchEvent(MotionEvent event) %7B%0A        int x = (int) event.getRawX();%0A        int y = (int) event.getRawY();%0A%0A        if (MotionEvent.ACTION_MOVE == event.getAction()) %7B%0A            int deltaX = x - mLastX;%0A            int deltaY = y - mLastY;%0A            setTranslationX(getTranslationX() + deltaX);%0A            setTranslationY(getTranslationY() + deltaY);%0A        %7D%0A%0A        if (MotionEvent.ACTION_UP == event.getAction()) %7B%0A            // make our onClickListener called%0A            callOnClick();%0A        %7D%0A%0A        mLastX = x;%0A        mLastY = y;%0A        return true;%0A    %7D
 %0A%7D%0A

make a view move with the finger