Gallery通過onFling設置滑動

設置滑動方法:

myGallery.onFling(null, null, -2000, 0);

第三個參數,數值是滑動距離
正數時:向左切換,
負數時:向右切換

看源碼發現,除了第三個參數其他三個參數都無用

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        
        if (!mShouldCallbackDuringFling) {
            // We want to suppress selection changes
            
            // Remove any future code to set mSuppressSelectionChanged = false
            removeCallbacks(mDisableSuppressSelectionChangedRunnable);

            // This will get reset once we scroll into slots
            if (!mSuppressSelectionChanged) mSuppressSelectionChanged = true;
        }
        
        // Fling the gallery!
        mFlingRunnable.startUsingVelocity((int) -velocityX);
        
        return true;
    }

總結下,爲什麼其他三個參數無效

1.先說第四個參數

Gallery,第一句描述就是A view that shows items in a center-locked, horizontally scrolling list

翻譯:一個鎖定豎直方向,水平方向滑動的列表view

第四個參數是設置豎直方向滑動距離,不符合鎖定豎直方向這一條。所以也沒用了

2.第一和第二個參數:
首先onFling方法中最終執行的代碼是下邊這句,

 mFlingRunnable.startUsingVelocity((int) -velocityX);

源碼中的startUsingVelocity方法

  		@UnsupportedAppUsage
        public void startUsingVelocity(int initialVelocity) {
            if (initialVelocity == 0) return;
            
            startCommon();
            
            int initialX = initialVelocity < 0 ? Integer.MAX_VALUE : 0;
            mLastFlingX = initialX;
            mScroller.fling(initialX, 0, initialVelocity, 0,
                    0, Integer.MAX_VALUE, 0, Integer.MAX_VALUE);
            post(this);
        }

這個方法裏最終調用的是Scrollerfling方法

這裏int initialX = initialVelocity < 0 ? Integer.MAX_VALUE : 0;

這裏設置了起始位置,是最大值還是0,

所以不需要第一 第二個參數的MotionEvent, 來提供水平的位置信息,而豎直方向不能滑動,所以也不需要。

所以你要是使用GalleryonFling方法,只要傳第三個參數就行了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章