Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smooth scroll does not work in ViewPager (support library)

I am writing application that uses ViewPager to host Fragments.

When I change fragment programmatically the smooth scroll function does not work. I use ViewPager.setCurrentItem(int item, boolean smoothScroll)` method.

Maybe anyone know a workaround this bug? Maybe with animations?

EDIT: I am using support package. And the issue is that whether I use ViewPager.setCurrentItem(2, true) or ViewPager.setCurrentItem(2, false) the result is the same. The view switches really fast (not smoothly).

like image 352
Tautvydas Avatar asked Aug 17 '12 15:08

Tautvydas


1 Answers

I've fixed this by creating a MyViewPager that overrides the ViewPager.mScroller using reflection.

public class MyViewPager extends ViewPager 
{
  public MyViewPager( Context context, AttributeSet attrs) 
  {
    super( context, attrs );
    setMyScroller();
  }
  private void setMyScroller() 
  {
    try 
    {
            Class<?> viewpager = ViewPager.class;
            Field scroller = viewpager.getDeclaredField("mScroller");
            scroller.setAccessible(true);
            scroller.set(this, new MyScroller(getContext()));
    } catch (Exception e) 
    {
        e.printStackTrace();
    }
  }

  public class MyScroller extends Scroller 
  {
    public MyScroller(Context context) 
    {
        super(context, new DecelerateInterpolator());
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy, int duration) 
    {
        super.startScroll(startX, startY, dx, dy, 1000 /*1 secs*/);
    }
  }
} 
like image 51
Marc Van Daele Avatar answered Oct 20 '22 04:10

Marc Van Daele