2011-01-14 60 views
1

如何让画廊控件一次滚动一个图像?还有什么是使这些图像连续循环的好方法?我尝试重写onFling,根本不起作用。Gallery一次滚动一个图像

这使图像移动一定距离但并未真正实现“真正的分页”。

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

      // return super.onFling(e1, e2, velocityX, velocityY); 
      int kEvent; 
       if(isScrollingLeft(e1, e2)){ //Check if scrolling left 
       kEvent = KeyEvent.KEYCODE_DPAD_LEFT; 
       } 
       else{ //Otherwise scrolling right 
       kEvent = KeyEvent.KEYCODE_DPAD_RIGHT; 
       } 
       onKeyDown(kEvent, null); 
       return true; 
     } 
     private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2){ 
       return e2.getX() > e1.getX(); 
      } 

回答

9

我创建了新的控件,将其命名为CustomGallery并从Gallery中扩展它。在自定义画廊我放置以下内容:

@Override 
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
     return super.onFling(e1, e2, 0, velocityY); 
     } 

在我的活动中,我使用CustomGallery而不是Gallery。这工作。有一件事,我们从2.2改为2.3(姜饼)。在我尝试覆盖onFling之前,它并不适用于我。所以我怀疑这也与操作系统的版本有关。

+2

难道你不认为如果你有333个意见是关于时间谷歌开始在这里更直接的解决方案工作? :) – dropsOfJupiter 2011-05-10 04:34:09

3

这一直在工作。在所有版本上不会失败。

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

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

@Override 
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 
     float velocityY) { 
    boolean leftScroll = isScrollingLeft(e1, e2); 
    boolean rightScroll = isScrollingRight(e1, e2); 

    if (rightScroll) { 
     if (getSelectedItemPosition() != 0)    
      setSelection(getSelectedItemPosition() - 1, true); 
    } else if (leftScroll) { 

     if (getSelectedItemPosition() != getCount() - 1) 
      setSelection(getSelectedItemPosition() + 1, true); 
    } 
    return true; 
} 
+1

你可以给一个示例项目,这是非常紧迫的 – VenomVendor 2012-01-27 09:08:33

5

Aniket Awati的解决方案对我来说最合适。不过,我会建议进行一项改进,以避免在某些情况下卷动两件物品。

int mSelection = 0; 

@Override 
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, 
     float velocityY) { 
    boolean leftScroll = isScrollingLeft(e1, e2); 
    boolean rightScroll = isScrollingRight(e1, e2); 

    if (rightScroll) { 
     if (mSelection != 0)    
      setSelection(--mSelection, true); 
    } else if (leftScroll) { 

     if (mSelection != getCount() - 1) 
      setSelection(++mSelection, true); 
    } 
    return false; 
} 
相关问题