Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop scrolling in a Gallery Widget?

I think I found a way to achieve both only scrolling 1 view at a time in the gallery and be able to have a minimal swipe length to trigger animation.

Override the onFling method of the gallery widget and instead of calling super.onFling, check to see whether or not the swipe was from left to right or right to left and call the appropriate dpad event as shown below:

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

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float 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;  
}

This is the code that worked for me.

Nadewad's solution + some animation speed adjustments:

Create class that extends Gallery, and override this metods:

  @Override
  public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
    setAnimationDuration(600);
    return super.onScroll(e1, e2, distanceX, distanceY);
  }

  @Override
  public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    float velMax = 2500f;
    float velMin = 1000f;
    float velX = Math.abs(velocityX);
    if (velX > velMax) {
      velX = velMax;
    } else if (velX < velMin) {
      velX = velMin;
    }
    velX -= 600;
    int k = 500000;
    int speed = (int) Math.floor(1f / velX * k);
    setAnimationDuration(speed);

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

Enjoy!


The easy way is following:

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

You also can check here: Android Infinite Loop Gallery


The easiest way I have found to accomplish this is by overriding the Gallery onFling method, and providing my own velocityX value:

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

It's not perfect, but it does the job. Ideally, you would probably write something custom for onFling to make it work exactly as you like.