使用反射机制修改viewPager切换滑动速度

ViewPager的惯性效果(滑到一定距离自动平滑到另一个pager,或者调用setCurrentItem)是通过scroller来实现的, 其中有个变量为mScroller,为了修改这个滑动的速度,需要改变mScroller的一些值,但是mScroller是私有变量,所以在不直接修改ViewPager源码的情况下,只能用反射修改mScroller。

自定义一个Scroller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class FixedSpeedScroller extends Scroller {
     private int mDuration = 1500;
                                                                                                            
     public FixedSpeedScroller(Context context) {
         super (context);
     }
                                                                                                            
     public FixedSpeedScroller(Context context, Interpolator interpolator) {
         super (context, interpolator);
     }
                                                                                                            
     @Override
     public void startScroll(int startX, int startY, int dx, int dy, int duration) {
         // Ignore received duration, use fixed one instead
         super .startScroll(startX, startY, dx, dy, mDuration);
     }
                                                                                                            
     @Override
     public void startScroll(int startX, int startY, int dx, int dy) {
         // Ignore received duration, use fixed one instead
         super .startScroll(startX, startY, dx, dy, mDuration);
     }
                                                                                                            
     public void setmDuration(int time) {
         mDuration = time;
     }
                                                                                                            
     public int getmDuration() {
         return mDuration;
     }
}


使用方法:

1
2
3
4
5
6
7
8
9
10
try {
                 Field field = ViewPager.class.getDeclaredField( "mScroller" );
                 field.setAccessible( true );
                 FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(),
                         new AccelerateInterpolator());
                 field.set(mViewPager, scroller);
                 scroller.setmDuration(2000);
             } catch (Exception e) {
                 LogUtils.e(TAG, "" , e);
             }

注意点:
PagerAdapter 的destroyItem 每次会删除上一个页面,导致,如果做自动切换页面时会看不到动画.

解决办法:
destoryItem中不做删除view,instantiateItem中对view是否有parent做为判断条件,这种情况适用于,少量的固定的子View,比如一个Banner,banner中做自动循环播放

你可能感兴趣的:(Android技术资料)