1. 程式人生 > >12.View的滑動

12.View的滑動

1.scrollTo和ScrollBy     為了實現滑動,View提供了兩個方法來讓我們實現這個功能,那就是scrollTo和scrollBy方法,     scrollTo的方法如下:      
/**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;
            mScrollY = y;
            //用於通知父控制元件需要清空這個View的快取
            invalidateParentCaches();
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            
            if (!awakenScrollBars()) {
                postInvalidateOnAnimation();
            }
        }
    }


    接下來我們來看這個方法,這個方法的引數x,y分別代表,我們想要讓這個View偏離最初位置的大小,比如x為100,那麼就偏離最初100個畫素點,其中,從左向右滑動是負的,從右向左是正的,View從上向下是負的,從下往上滑動是負的,    這個方法是絕對滑動,比如當前橫縱偏離都是90,這時候引數為scroll( 100 , 100 ) 那麼做的操作就是向上滑動10,向左滑動10,。     接下來我們看到invalidateParentCaches 這個方法,這個方法是用於通知父控制元件,當前的控制元件已經失效了,要讓父控制元件清空當前這個View的快取,並且重新建立這個View。     awakeScrollBars 返回為true代表著有動畫正在進行,為false就是其他情況。當有動畫在進行的時候,我們就不應該繼續執行滾動動畫,而當前沒有動畫在進行,我們就呼叫postInvalidateOnAnimation 這個,這個方法支援在非同步執行緒重新整理UI,並且帶有動畫效果。          接下來介紹scrollBy方法:    
    /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }



   可以看到,scrollBy方法就是基於scrollTo方法,scrollBy方法是相對偏移,比如當前滾動為90 90 ,我們需要呼叫scrollByt(10, 10 ) 結果,滾動偏移就成了100 , 100 。
2. 使用動畫     使用動畫也可以完成滑動效果,不過,動畫的互動感會比較弱,因為上面的第一種方法的滾動偏移量,是可以動態改變的,這意味著什麼?這意味著,我們可以在onTouchEvent去控制,可以結合使用者的手勢來完成各種滾動效果,在這邊,我們就暫時不詳細談了。接下來我們來複習下動畫的使用。     第一種方法是使用XML    
 <?xml version="1.0" encoding="utf-8"?>
     <set xmlns:android="http://schemas.android.com/apk/res/android"
            android:fillAfter="true"
            android:zAdjustment="normal">
            <translate
                android:duration="100"
                android:fromXDelta="0"
                android:formXDelta="0"
                android:interpolator="@android:anim/linear_interpolator"
                android:toXDelta="100"
                android:toYDelta="100"   />    
    </set>

        這個方法會讓我們把View從原始位置往下移動100個畫素 另外一種是使用屬性動畫         ObjectAnimator.ofFloat( tragetView,"translationX",0,100).setDuraltion( 100 ).start();     動畫的缺點主要是,執行動畫過程中,是不可逆的。  3.改變佈局引數  儘管這裡我不太願意介紹,但是,其實setLayoutParams也可以用於做動畫效果,但是,這邊不推薦使用,因為當你使用的是比較複雜的控制元件的時候,尤其是帶圖片資源,setLayoutParams帶來的開銷是很大的,耗費CPU資源較多,在一些低配置的機器上,執行的效果不理想。 但是,在使用拖拽效果的時候,一些小元素還是很適合用setLayoutParams的。                                    0.