2012-07-17 26 views
1

我跟隨此主題auto scroll a Gallery widget創建一個圖庫自動從左向右滾動5秒。這裏是我的畫廊:Android如何使Gallery自動滾動到第一項?

public class MyBannersGallery extends Gallery { 

private Handler handler; 

public MyBannersGallery(Context ctx, AttributeSet attrSet) { 
    super(ctx, attrSet); 
    handler = new Handler(); 
    postDelayedScrollNext(); 
} 

private void postDelayedScrollNext() { 
    handler.postDelayed(new Runnable() { 
     public void run() { 
      postDelayedScrollNext(); 
      onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null); 
     } 
    }, 5000); 

} 

private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) { 
    return e2.getX() > e1.getX(); 
} 

public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 
     float velocityY) { 
    int kEvent; 
    if (isScrollingLeft(e1, e2)) { 
     kEvent = KeyEvent.KEYCODE_DPAD_LEFT; 
    } else { 
     kEvent = KeyEvent.KEYCODE_DPAD_RIGHT; 
    } 
    onKeyDown(kEvent, null); 
    return true; 
} 

}

當滾動到我的走廊盡頭,它停了下來。現在我想檢測我的圖庫是否滾動到最後。如果是,則向左滾動到第一個項目。我應該編輯我的課程來存檔這個?

回答

1

Gallery從AdapterView擴展,因此您可以使用方法'getSelectedItemPosition()'來確定當前圖像索引的位置。所以也許這樣的事情會起作用?

private void postDelayedScrollNext() { 
    handler.postDelayed(new Runnable() { 
     public void run() { 
      // check to see if we are at the image is at the last index, if so set the 
      // selection back to 1st image. 
      if (getSelectedItemPosition() == getCount() - 1) { 
       setSelection(0); 
       postDelayedScrollNext(); 
       return; 
      } 
      postDelayedScrollNext(); 

      onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null); 
     } 
    }, 5000); 

} 

當然,這只是一個快速入侵。如果你想要很好的動畫,畫廊可以很好地滾動回第一項,那麼你必須做額外的工作,但想法是一樣的。

+0

謝謝。我也剛剛發現了getSelectedItemPosition()方法。無論如何感謝您的回覆。 – user1417127 2012-07-17 04:47:45

+1

我對postDelayedScrollNext()的工作方式感到困惑,如果它是關於每5秒自動滾動的,爲什麼我們需要onKeyDown(..) – 2013-10-01 09:07:50

0

對我來說這種形式的工作:

public MyBannersGallery(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    handler = new Handler(); 
    postDelayedScrollNext(0); 
} 

private void postDelayedScrollNext(final int position) { 
    handler.postDelayed(new Runnable() { 
     public void run() { 
      if (getSelectedItemPosition() == getCount() - 1) { 
       setSelection(0); 
       postDelayedScrollNext(0); 
       return; 
      } 
      setSelection(position+1); 
      postDelayedScrollNext(position+1); 

     } 
    }, 4000); 

} 
相關問題