如何通过编程实现滚动动画

9

我正在尝试通过编程实现画廊的滚动动画。

尝试使用setSelection(int pos, Boolean animate),但它不起作用。

有没有办法覆盖setSelection()方法。

5个回答

12

刚刚我遇到了这个问题。我需要移动画廊中的一个元素,所以对我来说最好的解决方案是模拟按键事件。

myGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
或者
myGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);

6

基于Kurru的出色思路,模拟单击下一个或上一个视图。

//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);       
}

6

Gallery.setSelection(int position, boolean animate);

请参考以下网址:http://groups.google.com/group/android-developers/browse_thread/thread/9140fd6af3061cdf/7f89e53ae53e455b?lnk=gst&q=setselection#7f89e53ae53e455b

解决方法:

如果你还在寻找,我有两种可能的解决方案,都略微不太理想:

(1) 你可以使用所选速度使画廊进行快速滑动,如下所示:

myGallery.onFling(null, null, velocity, 0);

通过调整速度,您可以设置值以向任一方向移动选择一个或两个。由于画廊自我居中,因此您不需要完全准确地获取目标。

(2) 由于画廊源代码是可用的,因此您可以修改它以实现自己的画廊。看起来您不需要添加太多代码即可控制快速滑动以便在您选择的位置结束。

我原本认为我必须执行(2),但发现对于我的问题,我可以使用(1)来解决。


方法(1)非常好用,只需确保使用足够大的速度即可。遗憾的是,这里的Android文档非常误导:“当发生fling事件时通知”在我看来是不正确的,应该说类似“告诉画廊执行fling”或者该方法应该被称为performFling。 - pheelicks

2
我正在查看画廊源代码,看是否能够实现此功能。这段代码似乎可以实现这个功能。但在我尝试使用时失败了。我似乎没有传递正确的坐标,所以res一直返回false。如果成功的话,应该会返回true。
我将此留在这里,以防其他人想要尝试修复它!(如果您成功了,请发布您的解决方案!)
Rect rect = new Rect();
gallery.getHitRect(rect);


int x = rect.centerX()+getWindowManager().getDefaultDisplay().getWidth();
int y = rect.centerY();

MotionEvent event = MotionEvent.obtain(100, 100, MotionEvent.ACTION_DOWN, x, y, 0);
timesGallery.onDown(event);
boolean res = timesGallery.onSingleTapUp(null);

2

我对“Kurru”提供的代码进行了少量修改,现在它可以正常工作。

Rect rect = new Rect();
    gallery.getHitRect(rect);

    int width = Math.abs(rect.width());
    if(!isForwardScroll){
        width = width * -1;
    }
    int x = rect.centerX()+width/2;
    int y = rect.centerY();

    MotionEvent event = MotionEvent.obtain(100, 100, MotionEvent.ACTION_DOWN, x, y, 0);
    gallery.onDown(event);
    boolean res = gallery.onSingleTapUp(null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接