I have to implement a gallery which moves to next slide on fling with animation. I have found some solutions here: How to have scrolling animation programmatically
I am using this code:
//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);
}
The problem is that it only works when I have 3 images visible and also apparently it doesn't even work on some devices.
BUT when I have my images shown one at a time (they occupy almost all of the device width) this method doesn't work. That is why I have implemented the following method:
@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;
}
using code from that other post: How to stop scrolling in a Gallery Widget?
OBJECTIVE: calculate the right velocityX to have a smooth scrolling from one slide to another, either left or right. Velocity is calculated in pixels / second. If the velocity I provide is too small then the image will scroll a bit and get back to the previous one. If the velocity is too big then it will scroll trough more than one image but I need it to go ONE BY ONE and scroll to the next/previous image even the distance is very small. I have found that trying, the best value is slightly larger than the devices width but I wonder if it will be the case for all the devices.