Created
October 5, 2015 07:09
-
-
Save bamssong/04b576ab8ce746c3ef53 to your computer and use it in GitHub Desktop.
android VerticalViewPager
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Uses a combination of a PageTransformer and swapping X & Y coordinates | |
| * of touch events to create the illusion of a vertically scrolling ViewPager. | |
| * | |
| * Requires API 11+ | |
| * | |
| */ | |
| public class VerticalViewPager extends ViewPager { | |
| public VerticalViewPager(Context context) { | |
| super(context); | |
| init(); | |
| } | |
| public VerticalViewPager(Context context, AttributeSet attrs) { | |
| super(context, attrs); | |
| init(); | |
| } | |
| private void init() { | |
| // The majority of the magic happens here | |
| setPageTransformer(true, new VerticalPageTransformer()); | |
| // The easiest way to get rid of the overscroll drawing that happens on the left and right | |
| setOverScrollMode(OVER_SCROLL_NEVER); | |
| } | |
| private class VerticalPageTransformer implements ViewPager.PageTransformer { | |
| @Override | |
| public void transformPage(View view, float position) { | |
| if (position < -1) { // [-Infinity,-1) | |
| // This page is way off-screen to the left. | |
| view.setAlpha(0); | |
| } else if (position <= 1) { // [-1,1] | |
| view.setAlpha(1); | |
| // Counteract the default slide transition | |
| view.setTranslationX(view.getWidth() * -position); | |
| //set Y position to swipe in from top | |
| float yPosition = position * view.getHeight(); | |
| view.setTranslationY(yPosition); | |
| } else { // (1,+Infinity] | |
| // This page is way off-screen to the right. | |
| view.setAlpha(0); | |
| } | |
| } | |
| } | |
| /** | |
| * Swaps the X and Y coordinates of your touch event. | |
| */ | |
| private MotionEvent swapXY(MotionEvent ev) { | |
| float width = getWidth(); | |
| float height = getHeight(); | |
| float newX = (ev.getY() / height) * width; | |
| float newY = (ev.getX() / width) * height; | |
| ev.setLocation(newX, newY); | |
| return ev; | |
| } | |
| @Override | |
| public boolean onInterceptTouchEvent(MotionEvent ev){ | |
| boolean intercepted = super.onInterceptTouchEvent(swapXY(ev)); | |
| swapXY(ev); // return touch coordinates to original reference frame for any child views | |
| return intercepted; | |
| } | |
| @Override | |
| public boolean onTouchEvent(MotionEvent ev) { | |
| return super.onTouchEvent(swapXY(ev)); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://stackoverflow.com/questions/13477820/android-vertical-viewpager