Android開發之Scroller

yungfan發表於2016-04-16

什麼是Scroller?

翻譯為彈性滑動物件,可以實現View的彈性滑動動畫,與Scroller相關的就是大家比較熟悉的scrollTo和scrollBy方法,可以用來實現View的滑動,但是它們的缺點就是瞬間完成,無法很平滑地過渡,而Scroller可以幫助我們很平滑地進行彈性滑動。

使用

一般使用在自定義View中較多,可以實現View的彈性滑動效果
1、自定義一個View,註釋很詳細

/**
 * 自定義View 裡面有個Scroller 它能實現非常平滑的滾動效果 就像動畫一樣 可以控制在多長時間內滾動到指定位置
 * 
 * @author yangfan
 * 
 */
public class DIYView extends LinearLayout
{

	// 建立一個Scroller
	private Scroller mScroller;

	public DIYView(Context context)
	{
		this(context, null);
	}

	// 1、建立Scroller
	public DIYView(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		mScroller = new Scroller(context);
	}

	// 2、觸控回撥,每次X軸方向加100,然後呼叫smoothScrollTo
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		int disX = mScroller.getFinalX() + 100;

		Log.e("***************", "onTouchEvent");
		smoothScrollTo(disX, 0);
		return super.onTouchEvent(event);
	}

	// 3、根據座標差 呼叫smoothScrollBy
	public void smoothScrollTo(int fx, int fy)
	{
		int dx = fx - mScroller.getFinalX();
		int dy = fy - mScroller.getFinalY();
		smoothScrollBy(dx, dy);
	}

	// 4、呼叫startScroll設定座標,然後invalidate重繪
	public void smoothScrollBy(int dx, int dy)
	{

		// 引數一:startX 引數二:startY為開始滾動的位置,dx,dy為滾動的偏移量, 1500ms為完成滾動的時間
		mScroller.startScroll(mScroller.getFinalX(), mScroller.getFinalY(), dx,
				dy, 3000);
		invalidate();
	}

	// 5、重繪過程會呼叫computeScroll 真正呼叫scrollTo進行滾動 然後再進行重繪
	@Override
	public void computeScroll()
	{

		// 判斷滾動是否完成 true就是未完成
		if (mScroller.computeScrollOffset())
		{

			scrollTo(mScroller.getCurrX(), mScroller.getCurrY());

			// 本案例中 呼叫postInvalidate和invalidate都可以
			invalidate();
		}
		super.computeScroll();
	}

}
複製程式碼

2、佈局中使用自定義View

<com.abc.edu.scroll.DIYView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff" >

    <!-- 弄一個提示文字 -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#ff0000"
        android:gravity="center"
        android:text="請向左滑動"
        android:textSize="30sp" />

</com.abc.edu.scroll.DIYView>
複製程式碼

3、測試執行,然後用手指在螢幕滑動幾下

Scroller.gif

注意點

Scroller本身並不能實現View的滑動,本質還是讓View重繪,重繪中呼叫View的computeScroll方法,在該方法中進行滑動方法的具體實現,然後再呼叫重繪函式,如此反覆才會在介面上形成不斷滑動的動畫。

相關文章