2012-09-13 29 views
2

我必須實施一個圖庫,該圖庫會隨着動畫一起移動到下一張幻燈片。我在這裏找到了一些解決方案: How to have scrolling animation programmaticallyAndroid圖庫文件格式:如何計算投擲速度所需的速度

我使用這個代碼:

//scroll forward or backward 
private void scroll(int type){ 
View selectedV = mG.getSelectedView(); 
int idx = mG.indexOfChild(selectedV); 
switch(type){ 
    case FORWARD: 
default: 
    if(idx<mG.getChildCount()-1) 
     idx++; 
    break; 
case BACKWARD: 
    if(idx>0) 
     idx--;   
    break; 
} 
//now scrolled view's child idx in gallery is gotten 
View nextView = mG.getChildAt(idx); 
//(x,y) in scrolled view is gotten 
int x = nextView.getLeft()+nextView.getWidth()/2; 
int y = nextView.getTop()+nextView.getHeight()/2; 
String out = String.format("x=%d, y=%d", x, y); 
Log.i(TAG+".scroll", out); 

//Kurru's simulating clicking view 
MotionEvent event = MotionEvent.obtain(100, 100, MotionEvent.ACTION_DOWN, x, y, 0); 
mG.onDown(event); 
boolean res = mG.onSingleTapUp(null); 
Log.i(TAG+".scroll", "onSingleTapUp return =" + res);  

}

的問題是,它只有當我有3張圖片可見,並且顯然也沒有關係」的作品甚至可以在某些設備上工作。

但是當我一次只顯示一個圖像(它們幾乎佔據了所有設備寬度)時,此方法不起作用。這就是爲什麼我已實現了以下方法:使用代碼從其他崗位

@Override 
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 
     float velocityY) { 

    if(e1 == null || e2 == null) return false; 
    if (isScrollingLeft(e1, e2)) { // Check if scrolling left 


     if(State.curentZoom==0) 
      return super.onFling(e1, e2, State.imgWidthBig*1.1f, 0); 
     else { 
      scroll(BACKWARD); 
      return true; 
     } 
    } else if (isScrollingRight(e1, e2)) { // Otherwise scrolling right 

     if(State.curentZoom==0) 
      return super.onFling(e1, e2, (-1)*State.imgWidthBig*1.1f, 0); 
     else { 
      scroll(FORWARD); 
      return true; 
     } 
    } else 
     return false; 

} 

How to stop scrolling in a Gallery Widget?

目的:計算權velocityX有一個平滑滾動,從一個幻燈片到另一個,或左或對。速度以像素/秒計算。如果我提供的速度太小,圖像將滾動一下並返回到前一個。如果速度太大,它會滾動一個以上的圖像,但我需要它一個接一個滾動到下一個/上一個圖像,即使距離很小。 我發現嘗試,最好的價值比設備寬度稍大,但我想知道是否所有設備都是這樣。

回答

3

晚會晚了一點。 AOSP提供了2個類來幫助你計算速度,VelocityTracker & ViewConfiguration。跟蹤器消耗MotionEvents並輸出X/Y速度。而ViewConfiguration爲不同的手勢類型聲明瞭閾值。

下面是一個簡單的例子,使用2個類來檢測一個扔手勢。

mVelocityTracker = VelocityTracker.obtain(); 
    mViewConfiguration = ViewConfiguration.get(mContext); 

    mListView.setOnTouchListener(new OnTouchListener() { 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 

      final int action = event.getActionMasked(); 
      mVelocityTracker.addMovement(event); 

      if (action == MotionEvent.ACTION_UP) { 
       mVelocityTracker.computeCurrentVelocity(1000, mViewConfiguration.getScaledMaximumFlingVelocity()); 
       if (mVelocityTracker.getXVelocity() > mViewConfiguration.getScaledMinimumFlingVelocity()) { 
        // horizontal fling! 
        return true; 
       } 
      } 
      return false; 
     } 
    }); 
+0

感謝速度跟蹤器的想法 – Diljeet