mt0s
mt0s

Reputation: 5821

Revert back to default ViewPager scroller

I used this answer from a stackoveflow question about enabling a custom Scroller for ViewPager's slide animation and it works smoothly. It extends Scroller's class and uses reflection to access the mScroller field.

What I want now is when some conditions have been met ( onTouch() and a timer ) to revert back to the default scroll animation.

Tried to clone the mScroller field :

        Interpolator decelerator = new DecelerateInterpolator();
    try {
        mScroller = ViewPager.class.getDeclaredField("mScroller");
        cloneDefaultScroller = mScroller;
        mScroller.setAccessible(true);
        scroller = new CarouselScroller(pager.getContext(), decelerator);
        mScroller.set(pager, scroller);
    } catch (NoSuchFieldException e) {
    } catch (IllegalArgumentException e) {
    } catch (IllegalAccessException e) {
    }

enable it again like this

            cloneDefaultScroller.setAccessible(true);
            Scroller scroller1 = new Scroller(this);
            cloneDefaultScroller.set(pager, scroller1)

where cloneDefaultScroller and mScroller are :

  Field mScroller;
  Field cloneDefaultScroller;

but what I get is a scroller that only moves a few pixels and I have to try like 10 times to have a "normal" scroll ( from one page to another ).

Anyone can help with that? Thank you

Upvotes: 0

Views: 247

Answers (1)

Selvin
Selvin

Reputation: 6797

First, try to rename mScroller to mScrollerField, for your sanity ... why? because it is just a field description from ViewPager class, not object behind the field. Now it is obvious that there is no need for cloneDefaultScroller (you don't need another field description from ViewPager class but rather the field value from the instance of ViewPager)

so code should looks like(get old and set new one):

Field mScrollerField;
Scroller mOldScroller;

Interpolator decelerator = new DecelerateInterpolator();
try {
        mScrollerField= ViewPager.class.getDeclaredField("mScroller");
        mScrollerField.setAccessible(true);
        mOldScroller = (Scroller)mScrollerField.get(pager); //getting old value
        scroller = new CarouselScroller(pager.getContext(), decelerator);
        mScrollerField.set(pager, scroller);
} catch (NoSuchFieldException e) {
        e.printStackTrace(); 
        /*IMPORTANT at least pass the exception to logcat also for your 
        sanity (fx: in next version of compat library the field could be renamed 
        to mTheScroller and you could get NPE in restore code and then ask 
        stupid(without logcat) questions on SO why ...*/
} catch (IllegalArgumentException e) {
        e.printStackTrace();
} catch (IllegalAccessException e) {
        e.printStackTrace();
}

and restore:

mScrollerField.set(pager, mOldScroller);

Upvotes: 1

Related Questions