天天看點

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("mMinimumVelocity ")

mMinimumVelocity.setAccessible(true)

val velocity = mMinimumVelocity.get(mViewPager)//擷取值

mMinimumVelocity.set(mViewPager, 5)//你定義的值