Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to customize the threshold for ViewPager scrolling?

Tags:

android

I am not able to find a way to change the touch threshold for scrolling pages in ViewPager: http://developer.android.com/reference/android/support/v4/view/ViewPager.html

Looking at the source code, ViewPager has a method called determineTargetPage that checks to see if the move touch gesture distance > threshold range, but looks like there's no way to modify this range.

Any suggestions on how I can control this threshold (if at all possible)?

like image 350
almalkawi Avatar asked Jul 31 '12 01:07

almalkawi


People also ask

How do I scroll in ViewPager?

One should use ViewPager2 and in its XML set android:orientation="vertical" property and your ViewPager will scroll vertically. The complete code will be like this.

How to add ViewPager in activity in android?

You can't use ViewPager to swipe between Activities . You need to convert each of you five Activities into Fragments , then combine everything in one FragmentActivity with the Adapter you use with ViewPager .


1 Answers

Going out on a bit of a limb here; I have no doubt that you may have to tweak this concept and/or code.

I will recommend what I did in the comments above; to extend ViewPager and override its public constructors, and call a custom method which is a clone of initViewPager() (seen in the source you provided). However, as you noted, mFlingDistance, mMinimumVelocity, and mMaximumVelocity are private fields, so they can't be accessed by a subclass.

(Note: You could also change these methods after the constructors are called, if you wanted to.)

Here's where it gets a bit tricky. In Android, we can use the Java Reflection API to make those fields accessible.

It should work something like this:

Class clss = getClass.getSuperClass();
Field flingField = clss.getDeclaredField("mFlingDistance"); // Of course create other variables for the other two fields
flingField.setAccessible(true);
flingField.setInt(this, <whatever int value you want>); // "this" must be the reference to the subclass object

Then, repeat this for the other two variables with whatever values you want. You may want to look at how these are calculated in the source.

Unfortunately, as much as I would like to recommend using Reflection to override the private method determineTargetPage(), I don't believe it's possible to do this--even with the expansive Reflection API.

like image 66
Cat Avatar answered Sep 29 '22 22:09

Cat