ViewPager滑动灵敏度调整的方法实力
时间:2022-01-13 09:41:50|栏目:Android代码|点击: 次
在项目中用到了Android的ViewPager组件,但是发现在滑动的时候不是特别流畅,有些小的滑动无法响应,于是考虑进行优化。
ViewPager 手指滑动切换时会不灵敏,我们查看ViewPager源码,切换的判断是由mFlingDistance和mMinimumVelocity决定的。
private int determineTargetPage(int currentPage, float pageOffset, int velocity, int deltaX) { int targetPage; if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { targetPage = velocity > 0 ? currentPage : currentPage + 1; } else { final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f; targetPage = currentPage + (int) (pageOffset + truncator); } ......
而mFlingDistance和mMinimumVelocity是类内部计算的,并没有公开接口提供设置。
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private static final int MIN_FLING_VELOCITY = 400; // dips void initViewPager() { mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density); mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density }
我们可以通过反射来调整这2个值,解决滑动灵敏度的问题
val mFlingDistance: Field mFlingDistance = ViewPager::class.java.getDeclaredField("mFlingDistance") mFlingDistance.setAccessible(true) val distance = mFlingDistance.get(mViewPager)//获取值 mFlingDistance.set(mViewPager, 10) //你定义的值 val mMinimumVelocity: Field mMinimumVelocity = ViewPager::class.java.getDeclaredField("mFlingDistance") mMinimumVelocity.setAccessible(true) val velocity = mMinimumVelocity.get(mViewPager)//获取值 mMinimumVelocity.set(mViewPager, 5)//你定义的值