参见英文答案 >
Change ViewPager animation duration when sliding programmatically5个
我正在使用ViewPager子类MyPager(几乎相同),并且我使用其setCurrentItem(int index,boolean smooth)方法,并将smooth参数设置为true.它实际上比参数设置为’false’更平滑,但我想增加动画持续时间以使转换更加明显.
我正在使用ViewPager子类MyPager(几乎相同),并且我使用其setCurrentItem(int index,boolean smooth)方法,并将smooth参数设置为true.它实际上比参数设置为’false’更平滑,但我想增加动画持续时间以使转换更加明显.
我从不同的帖子收集了一些信息,this solution看起来很完美.我最终得到了这段代码“
MyPager.java:
public class MyPager extends ViewPager { public MyPager(Context context,AttributeSet attrs) { super(context,attrs); this.enabled = true; postInitViewPager(); } private ScrollerCustomDuration mScroller = null; /** * Override the Scroller instance with our own class so we can change the * duration */ private void postInitViewPager() { try { Class<?> viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField("mScroller"); scroller.setAccessible(true); Field interpolator = viewpager.getDeclaredField("sInterpolator"); interpolator.setAccessible(true); mScroller = new ScrollerCustomDuration(getContext(),(Interpolator) interpolator.get(null)); scroller.set(this,mScroller); } catch (Exception e) { Log.e("MyPager",e.getMessage()); } } /** * Set the factor by which the duration will change */ public void setScrollDurationFactor(double scrollFactor) { mScroller.setScrollDurationFactor(scrollFactor); } }
ScrollerCustomDuration.java
public class ScrollerCustomDuration extends Scroller { private double mScrollFactor = 2; public ScrollerCustomDuration(Context context) { super(context); } public ScrollerCustomDuration(Context context,Interpolator interpolator) { super(context,interpolator); } public ScrollerCustomDuration(Context context,Interpolator interpolator,boolean flywheel) { super(context,interpolator,flywheel); } /** * Set the factor by which the duration will change */ public void setScrollDurationFactor(double scrollFactor) { mScrollFactor = scrollFactor; } @Override public void startScroll(int startX,int startY,int dx,int dy,int duration) { super.startScroll(startX,startY,dx,dy,(int) (duration * mScrollFactor)); } }
问题是,当通过行scrolller.set(this,mScroller)运行时,我无法摆脱这个异常; MyPager:
java.lang.IllegalArgumentException: invalid value for field
任何的想法?
解决方法
你能修改这部分代码并插入一个Log语句吗?
private void postInitViewPager() { try { Class<?> viewpager = ViewPager.class; Field scroller = viewpager.getDeclaredField("mScroller"); scroller.setAccessible(true); Field interpolator = viewpager.getDeclaredField("sInterpolator"); interpolator.setAccessible(true); mScroller = new ScrollerCustomDuration(getContext(),(Interpolator) interpolator.get(null)); Log.d("TAG","mScroller is: " + mScroller + "," + mScroller.getClass().getSuperclass().getCanonicalName() + "; this class is " + this + "," + getClass().getSuperclass().getCanonicalName()); scroller.set(this,mScroller); } catch (Exception e) { Log.e("MyPager",e.getMessage()); }
然后发布输出?
编辑:问题是导入语句不正确. mScroller是一个android.widget.Scroller,你不能给它分配一个com.WazaBe.HoloEverywhere.widget.Scroller.