我正在尝试通过编程实现画廊的滚动动画。
尝试使用setSelection(int pos, Boolean animate)
,但它不起作用。
有没有办法覆盖setSelection()
方法。
刚刚我遇到了这个问题。我需要移动画廊中的一个元素,所以对我来说最好的解决方案是模拟按键事件。
myGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
或者myGallery.onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
基于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);
}
Gallery.setSelection(int position, boolean animate);
解决方法:
如果你还在寻找,我有两种可能的解决方案,都略微不太理想:
(1) 你可以使用所选速度使画廊进行快速滑动,如下所示:
myGallery.onFling(null, null, velocity, 0);
通过调整速度,您可以设置值以向任一方向移动选择一个或两个。由于画廊自我居中,因此您不需要完全准确地获取目标。
(2) 由于画廊源代码是可用的,因此您可以修改它以实现自己的画廊。看起来您不需要添加太多代码即可控制快速滑动以便在您选择的位置结束。
我原本认为我必须执行(2),但发现对于我的问题,我可以使用(1)来解决。
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);
我对“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);