Note this class is currently under early design and 68 | * development. The API will likely change in later updates of 69 | * the compatibility library, requiring changes to the source code 70 | * of apps when they are compiled against the newer version.
71 | * 72 | *ViewPager is most often used in conjunction with {@link android.app.Fragment}, 73 | * which is a convenient way to supply and manage the lifecycle of each page. 74 | * There are standard adapters implemented for using fragments with the ViewPager, 75 | * which cover the most common use cases. These are 76 | * {@link android.support.v4.app.FragmentPagerAdapter}, 77 | * {@link android.support.v4.app.FragmentStatePagerAdapter}, 78 | * {@link android.support.v13.app.FragmentPagerAdapter}, and 79 | * {@link android.support.v13.app.FragmentStatePagerAdapter}; each of these 80 | * classes have simple code showing how to build a full user interface 81 | * with them. 82 | * 83 | *
Here is a more complicated example of ViewPager, using it in conjuction
84 | * with {@link android.app.ActionBar} tabs. You can find other examples of using
85 | * ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.
86 | *
87 | * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java
88 | * complete}
89 | */
90 | public class HorizontalViewPager extends ViewGroup {
91 |
92 | private static final String TAG = "HHH";
93 | private static final boolean DEBUG = false;
94 |
95 | private static final boolean USE_CACHE = false;
96 |
97 | private static final int DEFAULT_OFFSCREEN_PAGES = 1;
98 | private static final int MAX_SETTLE_DURATION = 600; // ms
99 | private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
100 |
101 | private static final int DEFAULT_GUTTER_SIZE = 16; // dips
102 |
103 | private static final int[] LAYOUT_ATTRS = new int[] {
104 | android.R.attr.layout_gravity
105 | };
106 |
107 | static class ItemInfo {
108 | Object object;
109 | int position;
110 | boolean scrolling;
111 | float widthFactor;
112 | float offset;
113 | }
114 |
115 | private static final Comparator
You should keep this limit low, especially if your pages have complex layouts. 552 | * This setting defaults to 1.
553 | * 554 | * @param limit How many pages will be kept offscreen in an idle state. 555 | */ 556 | public void setOffscreenPageLimit(int limit) { 557 | if (limit < DEFAULT_OFFSCREEN_PAGES) { 558 | Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + 559 | DEFAULT_OFFSCREEN_PAGES); 560 | limit = DEFAULT_OFFSCREEN_PAGES; 561 | } 562 | if (limit != mOffscreenPageLimit) { 563 | mOffscreenPageLimit = limit; 564 | populate(); 565 | } 566 | } 567 | 568 | /** 569 | * Set the margin between pages. 570 | * 571 | * @param marginPixels Distance between adjacent pages in pixels 572 | * @see #getPageMargin() 573 | * @see #setPageMarginDrawable(Drawable) 574 | * @see #setPageMarginDrawable(int) 575 | */ 576 | public void setPageMargin(int marginPixels) { 577 | final int oldMargin = mPageMargin; 578 | mPageMargin = marginPixels; 579 | 580 | final int width = getWidth(); 581 | recomputeScrollPosition(width, width, marginPixels, oldMargin); 582 | 583 | requestLayout(); 584 | } 585 | 586 | /** 587 | * Return the margin between pages. 588 | * 589 | * @return The size of the margin in pixels 590 | */ 591 | public int getPageMargin() { 592 | return mPageMargin; 593 | } 594 | 595 | /** 596 | * Set a drawable that will be used to fill the margin between pages. 597 | * 598 | * @param d Drawable to display between pages 599 | */ 600 | public void setPageMarginDrawable(Drawable d) { 601 | mMarginDrawable = d; 602 | if (d != null) refreshDrawableState(); 603 | setWillNotDraw(d == null); 604 | invalidate(); 605 | } 606 | 607 | /** 608 | * Set a drawable that will be used to fill the margin between pages. 609 | * 610 | * @param resId Resource ID of a drawable to display between pages 611 | */ 612 | public void setPageMarginDrawable(int resId) { 613 | setPageMarginDrawable(getContext().getResources().getDrawable(resId)); 614 | } 615 | 616 | @Override 617 | protected boolean verifyDrawable(Drawable who) { 618 | return super.verifyDrawable(who) || who == mMarginDrawable; 619 | } 620 | 621 | @Override 622 | protected void drawableStateChanged() { 623 | super.drawableStateChanged(); 624 | final Drawable d = mMarginDrawable; 625 | if (d != null && d.isStateful()) { 626 | d.setState(getDrawableState()); 627 | } 628 | } 629 | 630 | // We want the duration of the page snap animation to be influenced by the distance that 631 | // the screen has to travel, however, we don't want this duration to be effected in a 632 | // purely linear fashion. Instead, we use this method to moderate the effect that the distance 633 | // of travel has on the overall snap duration. 634 | float distanceInfluenceForSnapDuration(float f) { 635 | f -= 0.5f; // center the values about 0. 636 | f *= 0.3f * Math.PI / 2.0f; 637 | return (float) Math.sin(f); 638 | } 639 | 640 | /** 641 | * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 642 | * 643 | * @param x the number of pixels to scroll by on the X axis 644 | * @param y the number of pixels to scroll by on the Y axis 645 | */ 646 | void smoothScrollTo(int x, int y) { 647 | smoothScrollTo(x, y, 0); 648 | } 649 | 650 | /** 651 | * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. 652 | * 653 | * @param x the number of pixels to scroll by on the X axis 654 | * @param y the number of pixels to scroll by on the Y axis 655 | * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) 656 | */ 657 | void smoothScrollTo(int x, int y, int velocity) { 658 | if (getChildCount() == 0) { 659 | // Nothing to do. 660 | setScrollingCacheEnabled(false); 661 | return; 662 | } 663 | int sx = getScrollX(); 664 | int sy = getScrollY(); 665 | int dx = x - sx; 666 | int dy = y - sy; 667 | if (dx == 0 && dy == 0) { 668 | completeScroll(); 669 | populate(); 670 | setScrollState(SCROLL_STATE_IDLE); 671 | return; 672 | } 673 | 674 | setScrollingCacheEnabled(true); 675 | setScrollState(SCROLL_STATE_SETTLING); 676 | 677 | final int width = getWidth(); 678 | final int halfWidth = width / 2; 679 | final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); 680 | final float distance = halfWidth + halfWidth * 681 | distanceInfluenceForSnapDuration(distanceRatio); 682 | 683 | int duration = 0; 684 | velocity = Math.abs(velocity); 685 | if (velocity > 0) { 686 | duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 687 | } else { 688 | final float pageWidth = width * mAdapter.getPageWidth(mCurItem); 689 | final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin); 690 | duration = (int) ((pageDelta + 1) * 100); 691 | } 692 | duration = Math.min(duration, MAX_SETTLE_DURATION); 693 | 694 | mScroller.startScroll(sx, sy, dx, dy, duration); 695 | ViewCompat.postInvalidateOnAnimation(this); 696 | } 697 | 698 | ItemInfo addNewItem(int position, int index) { 699 | ItemInfo ii = new ItemInfo(); 700 | ii.position = position; 701 | ii.object = mAdapter.instantiateItem(this, position); 702 | ii.widthFactor = mAdapter.getPageWidth(position); 703 | if (index < 0 || index >= mItems.size()) { 704 | mItems.add(ii); 705 | } else { 706 | mItems.add(index, ii); 707 | } 708 | return ii; 709 | } 710 | 711 | void dataSetChanged() { 712 | // This method only gets called if our observer is attached, so mAdapter is non-null. 713 | 714 | boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 && 715 | mItems.size() < mAdapter.getCount(); 716 | int newCurrItem = mCurItem; 717 | 718 | boolean isUpdating = false; 719 | for (int i = 0; i < mItems.size(); i++) { 720 | final ItemInfo ii = mItems.get(i); 721 | final int newPos = mAdapter.getItemPosition(ii.object); 722 | 723 | if (newPos == PagerAdapter.POSITION_UNCHANGED) { 724 | continue; 725 | } 726 | 727 | if (newPos == PagerAdapter.POSITION_NONE) { 728 | mItems.remove(i); 729 | i--; 730 | 731 | if (!isUpdating) { 732 | mAdapter.startUpdate(this); 733 | isUpdating = true; 734 | } 735 | 736 | mAdapter.destroyItem(this, ii.position, ii.object); 737 | needPopulate = true; 738 | 739 | if (mCurItem == ii.position) { 740 | // Keep the current item in the valid range 741 | newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1)); 742 | needPopulate = true; 743 | } 744 | continue; 745 | } 746 | 747 | if (ii.position != newPos) { 748 | if (ii.position == mCurItem) { 749 | // Our current item changed position. Follow it. 750 | newCurrItem = newPos; 751 | } 752 | 753 | ii.position = newPos; 754 | needPopulate = true; 755 | } 756 | } 757 | 758 | if (isUpdating) { 759 | mAdapter.finishUpdate(this); 760 | } 761 | 762 | Collections.sort(mItems, COMPARATOR); 763 | 764 | if (needPopulate) { 765 | // Reset our known page widths; populate will recompute them. 766 | final int childCount = getChildCount(); 767 | for (int i = 0; i < childCount; i++) { 768 | final View child = getChildAt(i); 769 | final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 770 | if (!lp.isDecor) { 771 | lp.widthFactor = 0.f; 772 | } 773 | } 774 | 775 | setCurrentItemInternal(newCurrItem, false, true); 776 | requestLayout(); 777 | } 778 | } 779 | 780 | void populate() { 781 | populate(mCurItem); 782 | } 783 | 784 | void populate(int newCurrentItem) { 785 | ItemInfo oldCurInfo = null; 786 | if (mCurItem != newCurrentItem) { 787 | oldCurInfo = infoForPosition(mCurItem); 788 | mCurItem = newCurrentItem; 789 | } 790 | 791 | if (mAdapter == null) { 792 | return; 793 | } 794 | 795 | // Bail now if we are waiting to populate. This is to hold off 796 | // on creating views from the time the user releases their finger to 797 | // fling to a new position until we have finished the scroll to 798 | // that position, avoiding glitches from happening at that point. 799 | if (mPopulatePending) { 800 | if (DEBUG) Log.i(TAG, "populate is pending, skipping for now..."); 801 | return; 802 | } 803 | 804 | // Also, don't populate until we are attached to a window. This is to 805 | // avoid trying to populate before we have restored our view hierarchy 806 | // state and conflicting with what is restored. 807 | if (getWindowToken() == null) { 808 | return; 809 | } 810 | 811 | mAdapter.startUpdate(this); 812 | 813 | final int pageLimit = mOffscreenPageLimit; 814 | final int startPos = Math.max(0, mCurItem - pageLimit); 815 | final int N = mAdapter.getCount(); 816 | final int endPos = Math.min(N-1, mCurItem + pageLimit); 817 | 818 | // Locate the currently focused item or add it if needed. 819 | int curIndex = -1; 820 | ItemInfo curItem = null; 821 | for (curIndex = 0; curIndex < mItems.size(); curIndex++) { 822 | final ItemInfo ii = mItems.get(curIndex); 823 | if (ii.position >= mCurItem) { 824 | if (ii.position == mCurItem) curItem = ii; 825 | break; 826 | } 827 | } 828 | 829 | if (curItem == null && N > 0) { 830 | curItem = addNewItem(mCurItem, curIndex); 831 | } 832 | 833 | // Fill 3x the available width or up to the number of offscreen 834 | // pages requested to either side, whichever is larger. 835 | // If we have no current item we have no work to do. 836 | if (curItem != null) { 837 | float extraWidthLeft = 0.f; 838 | int itemIndex = curIndex - 1; 839 | ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 840 | final float leftWidthNeeded = 2.f - curItem.widthFactor; 841 | for (int pos = mCurItem - 1; pos >= 0; pos--) { 842 | if (extraWidthLeft >= leftWidthNeeded && pos < startPos) { 843 | if (ii == null) { 844 | break; 845 | } 846 | if (pos == ii.position && !ii.scrolling) { 847 | mItems.remove(itemIndex); 848 | mAdapter.destroyItem(this, pos, ii.object); 849 | itemIndex--; 850 | curIndex--; 851 | ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 852 | } 853 | } else if (ii != null && pos == ii.position) { 854 | extraWidthLeft += ii.widthFactor; 855 | itemIndex--; 856 | ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 857 | } else { 858 | ii = addNewItem(pos, itemIndex + 1); 859 | extraWidthLeft += ii.widthFactor; 860 | curIndex++; 861 | ii = itemIndex >= 0 ? mItems.get(itemIndex) : null; 862 | } 863 | } 864 | 865 | float extraWidthRight = curItem.widthFactor; 866 | itemIndex = curIndex + 1; 867 | if (extraWidthRight < 2.f) { 868 | ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 869 | for (int pos = mCurItem + 1; pos < N; pos++) { 870 | if (extraWidthRight >= 2.f && pos > endPos) { 871 | if (ii == null) { 872 | break; 873 | } 874 | if (pos == ii.position && !ii.scrolling) { 875 | mItems.remove(itemIndex); 876 | mAdapter.destroyItem(this, pos, ii.object); 877 | ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 878 | } 879 | } else if (ii != null && pos == ii.position) { 880 | extraWidthRight += ii.widthFactor; 881 | itemIndex++; 882 | ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 883 | } else { 884 | ii = addNewItem(pos, itemIndex); 885 | itemIndex++; 886 | extraWidthRight += ii.widthFactor; 887 | ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null; 888 | } 889 | } 890 | } 891 | 892 | calculatePageOffsets(curItem, curIndex, oldCurInfo); 893 | } 894 | 895 | if (DEBUG) { 896 | Log.i(TAG, "Current page list:"); 897 | for (int i=0; iA fake drag can be useful if you want to synchronize the motion of the ViewPager 2059 | * with the touch scrolling of another view, while still letting the ViewPager 2060 | * control the snapping motion and fling behavior. (e.g. parallax-scrolling tabs.) 2061 | * Call {@link #fakeDragBy(float)} to simulate the actual drag motion. Call 2062 | * {@link #endFakeDrag()} to complete the fake drag and fling as necessary. 2063 | * 2064 | *
During a fake drag the ViewPager will ignore all touch events. If a real drag
2065 | * is already in progress, this method will return false.
2066 | *
2067 | * @return true if the fake drag began successfully, false if it could not be started.
2068 | *
2069 | * @see #fakeDragBy(float)
2070 | * @see #endFakeDrag()
2071 | */
2072 | public boolean beginFakeDrag() {
2073 | if (mIsBeingDragged) {
2074 | return false;
2075 | }
2076 | mFakeDragging = true;
2077 | setScrollState(SCROLL_STATE_DRAGGING);
2078 | mInitialMotionX = mLastMotionX = 0;
2079 | if (mVelocityTracker == null) {
2080 | mVelocityTracker = VelocityTracker.obtain();
2081 | } else {
2082 | mVelocityTracker.clear();
2083 | }
2084 | final long time = SystemClock.uptimeMillis();
2085 | final MotionEvent ev = MotionEvent.obtain(time, time, MotionEvent.ACTION_DOWN, 0, 0, 0);
2086 | mVelocityTracker.addMovement(ev);
2087 | ev.recycle();
2088 | mFakeDragBeginTime = time;
2089 | return true;
2090 | }
2091 |
2092 | /**
2093 | * End a fake drag of the pager.
2094 | *
2095 | * @see #beginFakeDrag()
2096 | * @see #fakeDragBy(float)
2097 | */
2098 | public void endFakeDrag() {
2099 | if (!mFakeDragging) {
2100 | throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
2101 | }
2102 |
2103 | final VelocityTracker velocityTracker = mVelocityTracker;
2104 | velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
2105 | int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
2106 | velocityTracker, mActivePointerId);
2107 | mPopulatePending = true;
2108 | final int width = getWidth();
2109 | final int scrollX = getScrollX();
2110 | final ItemInfo ii = infoForCurrentScrollPosition();
2111 | final int currentPage = ii.position;
2112 | final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
2113 | final int totalDelta = (int) (mLastMotionX - mInitialMotionX);
2114 | int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
2115 | totalDelta);
2116 | setCurrentItemInternal(nextPage, true, true, initialVelocity);
2117 | endDrag();
2118 |
2119 | mFakeDragging = false;
2120 | }
2121 |
2122 | /**
2123 | * Fake drag by an offset in pixels. You must have called {@link #beginFakeDrag()} first.
2124 | *
2125 | * @param xOffset Offset in pixels to drag by.
2126 | * @see #beginFakeDrag()
2127 | * @see #endFakeDrag()
2128 | */
2129 | public void fakeDragBy(float xOffset) {
2130 | if (!mFakeDragging) {
2131 | throw new IllegalStateException("No fake drag in progress. Call beginFakeDrag first.");
2132 | }
2133 |
2134 | mLastMotionX += xOffset;
2135 |
2136 | float oldScrollX = getScrollX();
2137 | float scrollX = oldScrollX - xOffset;
2138 | final int width = getWidth();
2139 |
2140 | float leftBound = width * mFirstOffset;
2141 | float rightBound = width * mLastOffset;
2142 |
2143 | final ItemInfo firstItem = mItems.get(0);
2144 | final ItemInfo lastItem = mItems.get(mItems.size() - 1);
2145 | if (firstItem.position != 0) {
2146 | leftBound = firstItem.offset * width;
2147 | }
2148 | if (lastItem.position != mAdapter.getCount() - 1) {
2149 | rightBound = lastItem.offset * width;
2150 | }
2151 |
2152 | if (scrollX < leftBound) {
2153 | scrollX = leftBound;
2154 | } else if (scrollX > rightBound) {
2155 | scrollX = rightBound;
2156 | }
2157 | // Don't lose the rounded component
2158 | mLastMotionX += scrollX - (int) scrollX;
2159 | scrollTo((int) scrollX, getScrollY());
2160 | pageScrolled((int) scrollX);
2161 |
2162 | // Synthesize an event for the VelocityTracker.
2163 | final long time = SystemClock.uptimeMillis();
2164 | final MotionEvent ev = MotionEvent.obtain(mFakeDragBeginTime, time, MotionEvent.ACTION_MOVE,
2165 | mLastMotionX, 0, 0);
2166 | mVelocityTracker.addMovement(ev);
2167 | ev.recycle();
2168 | }
2169 |
2170 | /**
2171 | * Returns true if a fake drag is in progress.
2172 | *
2173 | * @return true if currently in a fake drag, false otherwise.
2174 | *
2175 | * @see #beginFakeDrag()
2176 | * @see #fakeDragBy(float)
2177 | * @see #endFakeDrag()
2178 | */
2179 | public boolean isFakeDragging() {
2180 | return mFakeDragging;
2181 | }
2182 |
2183 | private void onSecondaryPointerUp(MotionEvent ev) {
2184 | final int pointerIndex = MotionEventCompat.getActionIndex(ev);
2185 | final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
2186 | if (pointerId == mActivePointerId) {
2187 | // This was our active pointer going up. Choose a new
2188 | // active pointer and adjust accordingly.
2189 | final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2190 | mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
2191 | mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
2192 | if (mVelocityTracker != null) {
2193 | mVelocityTracker.clear();
2194 | }
2195 | }
2196 | }
2197 |
2198 | private void endDrag() {
2199 | mIsBeingDragged = false;
2200 | mIsUnableToDrag = false;
2201 |
2202 | if (mVelocityTracker != null) {
2203 | mVelocityTracker.recycle();
2204 | mVelocityTracker = null;
2205 | }
2206 | }
2207 |
2208 | private void setScrollingCacheEnabled(boolean enabled) {
2209 | if (mScrollingCacheEnabled != enabled) {
2210 | mScrollingCacheEnabled = enabled;
2211 | if (USE_CACHE) {
2212 | final int size = getChildCount();
2213 | for (int i = 0; i < size; ++i) {
2214 | final View child = getChildAt(i);
2215 | if (child.getVisibility() != GONE) {
2216 | child.setDrawingCacheEnabled(enabled);
2217 | }
2218 | }
2219 | }
2220 | }
2221 | }
2222 |
2223 | /**
2224 | * Tests scrollability within child views of v given a delta of dx.
2225 | *
2226 | * @param v View to test for horizontal scrollability
2227 | * @param checkV Whether the view v passed should itself be checked for scrollability (true),
2228 | * or just its children (false).
2229 | * @param dx Delta scrolled in pixels
2230 | * @param x X coordinate of the active touch point
2231 | * @param y Y coordinate of the active touch point
2232 | * @return true if child views of v can be scrolled by delta of dx.
2233 | */
2234 | protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
2235 | if (v instanceof ViewGroup) {
2236 | final ViewGroup group = (ViewGroup) v;
2237 | final int scrollX = v.getScrollX();
2238 | final int scrollY = v.getScrollY();
2239 | final int count = group.getChildCount();
2240 | // Count backwards - let topmost views consume scroll distance first.
2241 | for (int i = count - 1; i >= 0; i--) {
2242 | // TODO: Add versioned support here for transformed views.
2243 | // This will not work for transformed views in Honeycomb+
2244 | final View child = group.getChildAt(i);
2245 | if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
2246 | y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
2247 | canScroll(child, true, dx, x + scrollX - child.getLeft(),
2248 | y + scrollY - child.getTop())) {
2249 | return true;
2250 | }
2251 | }
2252 | }
2253 |
2254 | return checkV && ViewCompat.canScrollHorizontally(v, -dx);
2255 | }
2256 |
2257 | @Override
2258 | public boolean dispatchKeyEvent(KeyEvent event) {
2259 | // Let the focused view and/or our descendants get the key first
2260 | return super.dispatchKeyEvent(event) || executeKeyEvent(event);
2261 | }
2262 |
2263 | /**
2264 | * You can call this function yourself to have the scroll view perform
2265 | * scrolling from a key event, just as if the event had been dispatched to
2266 | * it by the view hierarchy.
2267 | *
2268 | * @param event The key event to execute.
2269 | * @return Return true if the event was handled, else false.
2270 | */
2271 | public boolean executeKeyEvent(KeyEvent event) {
2272 | boolean handled = false;
2273 | if (event.getAction() == KeyEvent.ACTION_DOWN) {
2274 | switch (event.getKeyCode()) {
2275 | case KeyEvent.KEYCODE_DPAD_LEFT:
2276 | handled = arrowScroll(FOCUS_LEFT);
2277 | break;
2278 | case KeyEvent.KEYCODE_DPAD_RIGHT:
2279 | handled = arrowScroll(FOCUS_RIGHT);
2280 | break;
2281 | case KeyEvent.KEYCODE_TAB:
2282 | if (Build.VERSION.SDK_INT >= 11) {
2283 | // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
2284 | // before Android 3.0. Ignore the tab key on those devices.
2285 | if (KeyEventCompat.hasNoModifiers(event)) {
2286 | handled = arrowScroll(FOCUS_FORWARD);
2287 | } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
2288 | handled = arrowScroll(FOCUS_BACKWARD);
2289 | }
2290 | }
2291 | break;
2292 | }
2293 | }
2294 | return handled;
2295 | }
2296 |
2297 | public boolean arrowScroll(int direction) {
2298 | View currentFocused = findFocus();
2299 | if (currentFocused == this) currentFocused = null;
2300 |
2301 | boolean handled = false;
2302 |
2303 | View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused,
2304 | direction);
2305 | if (nextFocused != null && nextFocused != currentFocused) {
2306 | if (direction == View.FOCUS_LEFT) {
2307 | // If there is nothing to the left, or this is causing us to
2308 | // jump to the right, then what we really want to do is page left.
2309 | final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
2310 | final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
2311 | if (currentFocused != null && nextLeft >= currLeft) {
2312 | handled = pageLeft();
2313 | } else {
2314 | handled = nextFocused.requestFocus();
2315 | }
2316 | } else if (direction == View.FOCUS_RIGHT) {
2317 | // If there is nothing to the right, or this is causing us to
2318 | // jump to the left, then what we really want to do is page right.
2319 | final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
2320 | final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
2321 | if (currentFocused != null && nextLeft <= currLeft) {
2322 | handled = pageRight();
2323 | } else {
2324 | handled = nextFocused.requestFocus();
2325 | }
2326 | }
2327 | } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) {
2328 | // Trying to move left and nothing there; try to page.
2329 | handled = pageLeft();
2330 | } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) {
2331 | // Trying to move right and nothing there; try to page.
2332 | handled = pageRight();
2333 | }
2334 | if (handled) {
2335 | playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction));
2336 | }
2337 | return handled;
2338 | }
2339 |
2340 | private Rect getChildRectInPagerCoordinates(Rect outRect, View child) {
2341 | if (outRect == null) {
2342 | outRect = new Rect();
2343 | }
2344 | if (child == null) {
2345 | outRect.set(0, 0, 0, 0);
2346 | return outRect;
2347 | }
2348 | outRect.left = child.getLeft();
2349 | outRect.right = child.getRight();
2350 | outRect.top = child.getTop();
2351 | outRect.bottom = child.getBottom();
2352 |
2353 | ViewParent parent = child.getParent();
2354 | while (parent instanceof ViewGroup && parent != this) {
2355 | final ViewGroup group = (ViewGroup) parent;
2356 | outRect.left += group.getLeft();
2357 | outRect.right += group.getRight();
2358 | outRect.top += group.getTop();
2359 | outRect.bottom += group.getBottom();
2360 |
2361 | parent = group.getParent();
2362 | }
2363 | return outRect;
2364 | }
2365 |
2366 | boolean pageLeft() {
2367 | if (mCurItem > 0) {
2368 | setCurrentItem(mCurItem-1, true);
2369 | return true;
2370 | }
2371 | return false;
2372 | }
2373 |
2374 | boolean pageRight() {
2375 | if (mAdapter != null && mCurItem < (mAdapter.getCount()-1)) {
2376 | setCurrentItem(mCurItem+1, true);
2377 | return true;
2378 | }
2379 | return false;
2380 | }
2381 |
2382 | /**
2383 | * We only want the current page that is being shown to be focusable.
2384 | */
2385 | @Override
2386 | public void addFocusables(ArrayList
36 |
37 |
38 | ## Screenshots
39 | For example, a DoubleViewPager with 4 horizontal x 4 vertical
40 |
41 |
42 |
43 | This is the structure.
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | }
7 | dependencies {
8 | classpath 'com.android.tools.build:gradle:1.3.0'
9 | // classpath 'org.codehaus.groovy:groovy-backports-compat23:2.3.5'
10 | // classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.2'
11 | // classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
12 | // NOTE: Do not place your application dependencies here; they belong
13 | // in the individual module build.gradle files
14 | }
15 | }
16 |
17 | allprojects {
18 | repositories {
19 | jcenter()
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m
13 | # org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juliome10/DoubleViewPager/b4027dc0ce3c52ddb4f5069cfb6d5708068b0e59/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Thu Oct 29 17:46:08 CET 2015
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/images/desc.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juliome10/DoubleViewPager/b4027dc0ce3c52ddb4f5069cfb6d5708068b0e59/images/desc.png
--------------------------------------------------------------------------------
/images/description.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juliome10/DoubleViewPager/b4027dc0ce3c52ddb4f5069cfb6d5708068b0e59/images/description.gif
--------------------------------------------------------------------------------
/images/google-play-badge.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/juliome10/DoubleViewPager/b4027dc0ce3c52ddb4f5069cfb6d5708068b0e59/images/google-play-badge.png
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':DoubleViewPagerSample', ':DoubleViewPager'
2 | //TO UPLOAD TO BINTRAY.
3 | // ONLY LIBRARY
4 | //include ':DoubleViewPager'
5 |
--------------------------------------------------------------------------------