diff --git a/src/android/support/v4/view/PagerAdapter.java b/src/android/support/v4/view/PagerAdapter.java
index 27eb227e..ef524047 100644
--- a/src/android/support/v4/view/PagerAdapter.java
+++ b/src/android/support/v4/view/PagerAdapter.java
@@ -24,7 +24,10 @@ import android.view.ViewGroup;
/**
* Base class providing the adapter to populate pages inside of
- * a {@link ViewPager}.
+ * a {@link ViewPager}. You will most likely want to use a more
+ * specific implementation of this, such as
+ * {@link android.support.v4.app.FragmentPagerAdapter} or
+ * {@link android.support.v4.app.FragmentStatePagerAdapter}.
*
*
When you implement a PagerAdapter, you must override the following methods
* at minimum:
@@ -73,7 +76,7 @@ import android.view.ViewGroup;
* the method {@link #getItemPosition(Object)}.
*/
public abstract class PagerAdapter {
- private final DataSetObservable mObservable = new DataSetObservable();
+ private DataSetObservable mObservable = new DataSetObservable();
public static final int POSITION_UNCHANGED = -1;
public static final int POSITION_NONE = -2;
@@ -89,6 +92,7 @@ public abstract class PagerAdapter {
* page views.
*/
public void startUpdate(ViewGroup container) {
+ startUpdate((View) container);
}
/**
@@ -102,7 +106,9 @@ public abstract class PagerAdapter {
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
- public abstract Object instantiateItem(ViewGroup container, int position);
+ public Object instantiateItem(ViewGroup container, int position) {
+ return instantiateItem((View) container, position);
+ }
/**
* Remove a page for the given position. The adapter is responsible
@@ -112,9 +118,11 @@ public abstract class PagerAdapter {
* @param container The containing View from which the page will be removed.
* @param position The page position to be removed.
* @param object The same object that was returned by
- * {@link #instantiateItem(ViewGroup, int)}.
+ * {@link #instantiateItem(View, int)}.
*/
- public abstract void destroyItem(ViewGroup container, int position, Object object);
+ public void destroyItem(ViewGroup container, int position, Object object) {
+ destroyItem((View) container, position, object);
+ }
/**
* Called to inform the adapter of which item is currently considered to
@@ -123,9 +131,10 @@ public abstract class PagerAdapter {
* @param container The containing View from which the page will be removed.
* @param position The page position that is now the primary.
* @param object The same object that was returned by
- * {@link #instantiateItem(ViewGroup, int)}.
+ * {@link #instantiateItem(View, int)}.
*/
public void setPrimaryItem(ViewGroup container, int position, Object object) {
+ setPrimaryItem((View) container, position, object);
}
/**
@@ -136,6 +145,77 @@ public abstract class PagerAdapter {
* page views.
*/
public void finishUpdate(ViewGroup container) {
+ finishUpdate((View) container);
+ }
+
+ /**
+ * Called when a change in the shown pages is going to start being made.
+ * @param container The containing View which is displaying this adapter's
+ * page views.
+ *
+ * @deprecated Use {@link #startUpdate(ViewGroup)}
+ */
+ public void startUpdate(View container) {
+ }
+
+ /**
+ * Create the page for the given position. The adapter is responsible
+ * for adding the view to the container given here, although it only
+ * must ensure this is done by the time it returns from
+ * {@link #finishUpdate(ViewGroup)}.
+ *
+ * @param container The containing View in which the page will be shown.
+ * @param position The page position to be instantiated.
+ * @return Returns an Object representing the new page. This does not
+ * need to be a View, but can be some other container of the page.
+ *
+ * @deprecated Use {@link #instantiateItem(ViewGroup, int)}
+ */
+ public Object instantiateItem(View container, int position) {
+ throw new UnsupportedOperationException(
+ "Required method instantiateItem was not overridden");
+ }
+
+ /**
+ * Remove a page for the given position. The adapter is responsible
+ * for removing the view from its container, although it only must ensure
+ * this is done by the time it returns from {@link #finishUpdate(View)}.
+ *
+ * @param container The containing View from which the page will be removed.
+ * @param position The page position to be removed.
+ * @param object The same object that was returned by
+ * {@link #instantiateItem(View, int)}.
+ *
+ * @deprecated Use {@link #destroyItem(ViewGroup, int, Object)}
+ */
+ public void destroyItem(View container, int position, Object object) {
+ throw new UnsupportedOperationException("Required method destroyItem was not overridden");
+ }
+
+ /**
+ * Called to inform the adapter of which item is currently considered to
+ * be the "primary", that is the one show to the user as the current page.
+ *
+ * @param container The containing View from which the page will be removed.
+ * @param position The page position that is now the primary.
+ * @param object The same object that was returned by
+ * {@link #instantiateItem(View, int)}.
+ *
+ * @deprecated Use {@link #setPrimaryItem(ViewGroup, int, Object)}
+ */
+ public void setPrimaryItem(View container, int position, Object object) {
+ }
+
+ /**
+ * Called when the a change in the shown pages has been completed. At this
+ * point you must ensure that all of the pages have actually been added or
+ * removed from the container as appropriate.
+ * @param container The containing View which is displaying this adapter's
+ * page views.
+ *
+ * @deprecated Use {@link #finishUpdate(ViewGroup)}
+ */
+ public void finishUpdate(View container) {
}
/**
@@ -149,15 +229,6 @@ public abstract class PagerAdapter {
*/
public abstract boolean isViewFromObject(View view, Object object);
- /**
- * This method will be invoked when a new page becomes selected. Animation is not
- * necessarily complete.
- *
- * @param position Position index of the new selected page.
- */
- public void onPageSelected(int position) {
- }
-
/**
* Save any instance state associated with this adapter and its pages that should be
* restored if the current UI state needs to be reconstructed.
@@ -188,7 +259,7 @@ public abstract class PagerAdapter {
* change position and always returns {@link #POSITION_UNCHANGED}.
*
* @param object Object representing an item, previously returned by a call to
- * {@link #instantiateItem(ViewGroup, int)}.
+ * {@link #instantiateItem(View, int)}.
* @return object's new position index from [0, {@link #getCount()}),
* {@link #POSITION_UNCHANGED} if the object's position has not changed,
* or {@link #POSITION_NONE} if the item is no longer present.
@@ -205,11 +276,21 @@ public abstract class PagerAdapter {
mObservable.notifyChanged();
}
- void registerDataSetObserver(DataSetObserver observer) {
+ /**
+ * Register an observer to receive callbacks related to the adapter's data changing.
+ *
+ * @param observer The {@link android.database.DataSetObserver} which will receive callbacks.
+ */
+ public void registerDataSetObserver(DataSetObserver observer) {
mObservable.registerObserver(observer);
}
- void unregisterDataSetObserver(DataSetObserver observer) {
+ /**
+ * Unregister an observer from callbacks related to the adapter's data changing.
+ *
+ * @param observer The {@link android.database.DataSetObserver} which will be unregistered.
+ */
+ public void unregisterDataSetObserver(DataSetObserver observer) {
mObservable.unregisterObserver(observer);
}
@@ -225,4 +306,15 @@ public abstract class PagerAdapter {
public CharSequence getPageTitle(int position) {
return null;
}
+
+ /**
+ * Returns the proportional width of a given page as a percentage of the
+ * ViewPager's measured width from (0.f-1.f]
+ *
+ * @param position The position of the page requested
+ * @return Proportional width for the given page position
+ */
+ public float getPageWidth(int position) {
+ return 1.f;
+ }
}
diff --git a/src/android/support/v4/view/ViewPager.java b/src/android/support/v4/view/ViewPager.java
index 4943d3f5..f19104a7 100644
--- a/src/android/support/v4/view/ViewPager.java
+++ b/src/android/support/v4/view/ViewPager.java
@@ -17,15 +17,25 @@
package android.support.v4.view;
import android.content.Context;
+import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
+import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
+import android.support.annotation.CallSuper;
+import android.support.annotation.DrawableRes;
+import android.support.v4.os.ParcelableCompat;
+import android.support.v4.os.ParcelableCompatCreatorCallbacks;
+import android.support.v4.view.accessibility.AccessibilityEventCompat;
+import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
+import android.support.v4.view.accessibility.AccessibilityRecordCompat;
+import android.support.v4.widget.EdgeEffectCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.FocusFinder;
@@ -41,11 +51,12 @@ import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
import android.view.animation.Interpolator;
import android.widget.Scroller;
-import android.widget.EdgeEffect;
+
+import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
-import ch.blinkenlights.android.vanilla.CompatHoneycomb;
+import java.util.List;
/**
* Layout manager that allows the user to flip left and right
@@ -57,9 +68,25 @@ import ch.blinkenlights.android.vanilla.CompatHoneycomb;
* the compatibility library, requiring changes to the source code
* of apps when they are compiled against the newer version.
*
- * Here is a more complicated example of ViewPager, using it in conjuction
+ *
ViewPager is most often used in conjunction with {@link android.app.Fragment},
+ * which is a convenient way to supply and manage the lifecycle of each page.
+ * There are standard adapters implemented for using fragments with the ViewPager,
+ * which cover the most common use cases. These are
+ * {@link android.support.v4.app.FragmentPagerAdapter} and
+ * {@link android.support.v4.app.FragmentStatePagerAdapter}; each of these
+ * classes have simple code showing how to build a full user interface
+ * with them.
+ *
+ *
For more information about how to use ViewPager, read Creating Swipe Views with
+ * Tabs.
+ *
+ * Below is a more complicated example of ViewPager, using it in conjunction
* with {@link android.app.ActionBar} tabs. You can find other examples of using
* ViewPager in the API 4+ Support Demos and API 13+ Support Demos sample code.
+ *
+ * {@sample development/samples/Support13Demos/src/com/example/android/supportv13/app/ActionBarTabsPager.java
+ * complete}
*/
public class ViewPager extends ViewGroup {
private static final String TAG = "ViewPager";
@@ -71,24 +98,36 @@ public class ViewPager extends ViewGroup {
private static final int MAX_SETTLE_DURATION = 600; // ms
private static final int MIN_DISTANCE_FOR_FLING = 25; // dips
+ private static final int DEFAULT_GUTTER_SIZE = 16; // dips
+
+ private static final int MIN_FLING_VELOCITY = 400; // dips
+
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.layout_gravity
};
+ /**
+ * Used to track what the expected number of items in the adapter should be.
+ * If the app changes this when we don't expect it, we'll throw a big obnoxious exception.
+ */
+ private int mExpectedAdapterCount;
+
static class ItemInfo {
Object object;
int position;
boolean scrolling;
+ float widthFactor;
+ float offset;
}
private static final Comparator COMPARATOR = new Comparator(){
@Override
public int compare(ItemInfo lhs, ItemInfo rhs) {
return lhs.position - rhs.position;
- }};
+ }
+ };
private static final Interpolator sInterpolator = new Interpolator() {
- @Override
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
@@ -96,6 +135,9 @@ public class ViewPager extends ViewGroup {
};
private final ArrayList mItems = new ArrayList();
+ private final ItemInfo mTempItem = new ItemInfo();
+
+ private final Rect mTempRect = new Rect();
private PagerAdapter mAdapter;
private int mCurItem; // Index of currently displayed page.
@@ -110,6 +152,12 @@ public class ViewPager extends ViewGroup {
private int mTopPageBounds;
private int mBottomPageBounds;
+ // Offsets of the first and last items, if known.
+ // Set during population, used to determine if we are at the beginning
+ // or end of the pager data set during touch scrolling.
+ private float mFirstOffset = -Float.MAX_VALUE;
+ private float mLastOffset = Float.MAX_VALUE;
+
private int mChildWidthMeasureSpec;
private int mChildHeightMeasureSpec;
private boolean mInLayout;
@@ -117,18 +165,20 @@ public class ViewPager extends ViewGroup {
private boolean mScrollingCacheEnabled;
private boolean mPopulatePending;
- private boolean mScrolling;
private int mOffscreenPageLimit = DEFAULT_OFFSCREEN_PAGES;
private boolean mIsBeingDragged;
private boolean mIsUnableToDrag;
+ private int mDefaultGutterSize;
+ private int mGutterSize;
private int mTouchSlop;
- private float mInitialMotionX;
/**
* Position of the last motion event.
*/
private float mLastMotionX;
private float mLastMotionY;
+ private float mInitialMotionX;
+ private float mInitialMotionY;
/**
* ID of the active pointer. This is used to retain consistency during
* drags/flings if multiple pointers are used.
@@ -147,20 +197,37 @@ public class ViewPager extends ViewGroup {
private int mMinimumVelocity;
private int mMaximumVelocity;
private int mFlingDistance;
+ private int mCloseEnough;
+
+ // If the pager is at least this close to its final position, complete the scroll
+ // on touch down and let the user interact with the content inside instead of
+ // "catching" the flinging pager.
+ private static final int CLOSE_ENOUGH = 2; // dp
private boolean mFakeDragging;
private long mFakeDragBeginTime;
- private EdgeEffect mLeftEdge;
- private EdgeEffect mRightEdge;
+ private EdgeEffectCompat mLeftEdge;
+ private EdgeEffectCompat mRightEdge;
private boolean mFirstLayout = true;
+ private boolean mNeedCalculatePageOffsets = false;
private boolean mCalledSuper;
private int mDecorChildCount;
+ private List mOnPageChangeListeners;
private OnPageChangeListener mOnPageChangeListener;
private OnPageChangeListener mInternalPageChangeListener;
private OnAdapterChangeListener mAdapterChangeListener;
+ private PageTransformer mPageTransformer;
+ private Method mSetChildrenDrawingOrderEnabled;
+
+ private static final int DRAW_ORDER_DEFAULT = 0;
+ private static final int DRAW_ORDER_FORWARD = 1;
+ private static final int DRAW_ORDER_REVERSE = 2;
+ private int mDrawingOrder;
+ private ArrayList mDrawingOrderedChildren;
+ private static final ViewPositionComparator sPositionComparator = new ViewPositionComparator();
/**
* Indicates that the pager is in an idle, settled state. The current page
@@ -178,6 +245,13 @@ public class ViewPager extends ViewGroup {
*/
public static final int SCROLL_STATE_SETTLING = 2;
+ private final Runnable mEndScrollRunnable = new Runnable() {
+ public void run() {
+ setScrollState(SCROLL_STATE_IDLE);
+ populate();
+ }
+ };
+
private int mScrollState = SCROLL_STATE_IDLE;
/**
@@ -217,6 +291,49 @@ public class ViewPager extends ViewGroup {
public void onPageScrollStateChanged(int state);
}
+ /**
+ * Simple implementation of the {@link OnPageChangeListener} interface with stub
+ * implementations of each method. Extend this if you do not intend to override
+ * every method of {@link OnPageChangeListener}.
+ */
+ public static class SimpleOnPageChangeListener implements OnPageChangeListener {
+ @Override
+ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
+ // This space for rent
+ }
+
+ @Override
+ public void onPageSelected(int position) {
+ // This space for rent
+ }
+
+ @Override
+ public void onPageScrollStateChanged(int state) {
+ // This space for rent
+ }
+ }
+
+ /**
+ * A PageTransformer is invoked whenever a visible/attached page is scrolled.
+ * This offers an opportunity for the application to apply a custom transformation
+ * to the page views using animation properties.
+ *
+ * As property animation is only supported as of Android 3.0 and forward,
+ * setting a PageTransformer on a ViewPager on earlier platform versions will
+ * be ignored.
+ */
+ public interface PageTransformer {
+ /**
+ * Apply a property transformation to the given page.
+ *
+ * @param page Apply the transformation to this page
+ * @param position Position of page relative to the current front-and-center
+ * position of the pager. 0 is front and center. 1 is one full
+ * page position to the right, and -1 is one page position to the left.
+ */
+ public void transformPage(View page, float position);
+ }
+
/**
* Used internally to monitor when adapters are switched.
*/
@@ -247,16 +364,31 @@ public class ViewPager extends ViewGroup {
final Context context = getContext();
mScroller = new Scroller(context, sInterpolator);
final ViewConfiguration configuration = ViewConfiguration.get(context);
- mTouchSlop = configuration.getScaledPagingTouchSlop();
- mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
- mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
- if (Build.VERSION.SDK_INT >= 14) {
- mLeftEdge = new EdgeEffect(context);
- mRightEdge = new EdgeEffect(context);
- }
-
final float density = context.getResources().getDisplayMetrics().density;
+
+ mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
+ mMinimumVelocity = (int) (MIN_FLING_VELOCITY * density);
+ mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
+ mLeftEdge = new EdgeEffectCompat(context);
+ mRightEdge = new EdgeEffectCompat(context);
+
mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density);
+ mCloseEnough = (int) (CLOSE_ENOUGH * density);
+ mDefaultGutterSize = (int) (DEFAULT_GUTTER_SIZE * density);
+
+ ViewCompat.setAccessibilityDelegate(this, new MyAccessibilityDelegate());
+
+ if (ViewCompat.getImportantForAccessibility(this)
+ == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
+ ViewCompat.setImportantForAccessibility(this,
+ ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
+ }
+ }
+
+ @Override
+ protected void onDetachedFromWindow() {
+ removeCallbacks(mEndScrollRunnable);
+ super.onDetachedFromWindow();
}
private void setScrollState(int newState) {
@@ -265,9 +397,11 @@ public class ViewPager extends ViewGroup {
}
mScrollState = newState;
- if (mOnPageChangeListener != null) {
- mOnPageChangeListener.onPageScrollStateChanged(newState);
+ if (mPageTransformer != null) {
+ // PageTransformers can do complex things that benefit from hardware layers.
+ enableLayers(newState != SCROLL_STATE_IDLE);
}
+ dispatchOnScrollStateChanged(newState);
}
/**
@@ -292,6 +426,7 @@ public class ViewPager extends ViewGroup {
final PagerAdapter oldAdapter = mAdapter;
mAdapter = adapter;
+ mExpectedAdapterCount = 0;
if (mAdapter != null) {
if (mObserver == null) {
@@ -299,14 +434,19 @@ public class ViewPager extends ViewGroup {
}
mAdapter.registerDataSetObserver(mObserver);
mPopulatePending = false;
+ final boolean wasFirstLayout = mFirstLayout;
+ mFirstLayout = true;
+ mExpectedAdapterCount = mAdapter.getCount();
if (mRestoredCurItem >= 0) {
mAdapter.restoreState(mRestoredAdapterState, mRestoredClassLoader);
setCurrentItemInternal(mRestoredCurItem, false, true);
mRestoredCurItem = -1;
mRestoredAdapterState = null;
mRestoredClassLoader = null;
- } else {
+ } else if (!wasFirstLayout) {
populate();
+ } else {
+ requestLayout();
}
}
@@ -339,10 +479,14 @@ public class ViewPager extends ViewGroup {
mAdapterChangeListener = listener;
}
+ private int getClientWidth() {
+ return getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
+ }
+
/**
* Set the currently selected page. If the ViewPager has already been through its first
- * layout there will be a smooth animated transition between the current item and the
- * specified item.
+ * layout with its current adapter there will be a smooth animated transition between
+ * the current item and the specified item.
*
* @param item Item index to select
*/
@@ -379,6 +523,7 @@ public class ViewPager extends ViewGroup {
setScrollingCacheEnabled(false);
return;
}
+
if (item < 0) {
item = 0;
} else if (item >= mAdapter.getCount()) {
@@ -394,32 +539,42 @@ public class ViewPager extends ViewGroup {
}
}
final boolean dispatchSelected = mCurItem != item;
- mCurItem = item;
- populate();
- final int destX = (getWidth() + mPageMargin) * item;
+
+ if (mFirstLayout) {
+ // We don't have any idea how big we are yet and shouldn't have any pages either.
+ // Just set things up and let the pending layout handle things.
+ mCurItem = item;
+ if (dispatchSelected) {
+ dispatchOnPageSelected(item);
+ }
+ requestLayout();
+ } else {
+ populate(item);
+ scrollToItem(item, smoothScroll, velocity, dispatchSelected);
+ }
+ }
+
+ private void scrollToItem(int item, boolean smoothScroll, int velocity,
+ boolean dispatchSelected) {
+ final ItemInfo curInfo = infoForPosition(item);
+ int destX = 0;
+ if (curInfo != null) {
+ final int width = getClientWidth();
+ destX = (int) (width * Math.max(mFirstOffset,
+ Math.min(curInfo.offset, mLastOffset)));
+ }
if (smoothScroll) {
smoothScrollTo(destX, 0, velocity);
- if (dispatchSelected && mOnPageChangeListener != null) {
- mOnPageChangeListener.onPageSelected(item);
- }
- if (dispatchSelected && mInternalPageChangeListener != null) {
- mInternalPageChangeListener.onPageSelected(item);
- }
if (dispatchSelected) {
- mAdapter.onPageSelected(item);
+ dispatchOnPageSelected(item);
}
} else {
- if (dispatchSelected && mOnPageChangeListener != null) {
- mOnPageChangeListener.onPageSelected(item);
- }
- if (dispatchSelected && mInternalPageChangeListener != null) {
- mInternalPageChangeListener.onPageSelected(item);
- }
if (dispatchSelected) {
- mAdapter.onPageSelected(item);
+ dispatchOnPageSelected(item);
}
- completeScroll();
+ completeScroll(false);
scrollTo(destX, 0);
+ pageScrolled(destX);
}
}
@@ -428,11 +583,105 @@ public class ViewPager extends ViewGroup {
* scrolled. See {@link OnPageChangeListener}.
*
* @param listener Listener to set
+ *
+ * @deprecated Use {@link #addOnPageChangeListener(OnPageChangeListener)}
+ * and {@link #removeOnPageChangeListener(OnPageChangeListener)} instead.
*/
+ @Deprecated
public void setOnPageChangeListener(OnPageChangeListener listener) {
mOnPageChangeListener = listener;
}
+ /**
+ * Add a listener that will be invoked whenever the page changes or is incrementally
+ * scrolled. See {@link OnPageChangeListener}.
+ *
+ * Components that add a listener should take care to remove it when finished.
+ * Other components that take ownership of a view may call {@link #clearOnPageChangeListeners()}
+ * to remove all attached listeners.
+ *
+ * @param listener listener to add
+ */
+ public void addOnPageChangeListener(OnPageChangeListener listener) {
+ if (mOnPageChangeListeners == null) {
+ mOnPageChangeListeners = new ArrayList<>();
+ }
+ mOnPageChangeListeners.add(listener);
+ }
+
+ /**
+ * Remove a listener that was previously added via
+ * {@link #addOnPageChangeListener(OnPageChangeListener)}.
+ *
+ * @param listener listener to remove
+ */
+ public void removeOnPageChangeListener(OnPageChangeListener listener) {
+ if (mOnPageChangeListeners != null) {
+ mOnPageChangeListeners.remove(listener);
+ }
+ }
+
+ /**
+ * Remove all listeners that are notified of any changes in scroll state or position.
+ */
+ public void clearOnPageChangeListeners() {
+ if (mOnPageChangeListeners != null) {
+ mOnPageChangeListeners.clear();
+ }
+ }
+
+ /**
+ * Set a {@link PageTransformer} that will be called for each attached page whenever
+ * the scroll position is changed. This allows the application to apply custom property
+ * transformations to each page, overriding the default sliding look and feel.
+ *
+ * Note: Prior to Android 3.0 the property animation APIs did not exist.
+ * As a result, setting a PageTransformer prior to Android 3.0 (API 11) will have no effect.
+ *
+ * @param reverseDrawingOrder true if the supplied PageTransformer requires page views
+ * to be drawn from last to first instead of first to last.
+ * @param transformer PageTransformer that will modify each page's animation properties
+ */
+ public void setPageTransformer(boolean reverseDrawingOrder, PageTransformer transformer) {
+ if (Build.VERSION.SDK_INT >= 11) {
+ final boolean hasTransformer = transformer != null;
+ final boolean needsPopulate = hasTransformer != (mPageTransformer != null);
+ mPageTransformer = transformer;
+ setChildrenDrawingOrderEnabledCompat(hasTransformer);
+ if (hasTransformer) {
+ mDrawingOrder = reverseDrawingOrder ? DRAW_ORDER_REVERSE : DRAW_ORDER_FORWARD;
+ } else {
+ mDrawingOrder = DRAW_ORDER_DEFAULT;
+ }
+ if (needsPopulate) populate();
+ }
+ }
+
+ void setChildrenDrawingOrderEnabledCompat(boolean enable) {
+ if (Build.VERSION.SDK_INT >= 7) {
+ if (mSetChildrenDrawingOrderEnabled == null) {
+ try {
+ mSetChildrenDrawingOrderEnabled = ViewGroup.class.getDeclaredMethod(
+ "setChildrenDrawingOrderEnabled", new Class[] { Boolean.TYPE });
+ } catch (NoSuchMethodException e) {
+ Log.e(TAG, "Can't find setChildrenDrawingOrderEnabled", e);
+ }
+ }
+ try {
+ mSetChildrenDrawingOrderEnabled.invoke(this, enable);
+ } catch (Exception e) {
+ Log.e(TAG, "Error changing children drawing order", e);
+ }
+ }
+ }
+
+ @Override
+ protected int getChildDrawingOrder(int childCount, int i) {
+ final int index = mDrawingOrder == DRAW_ORDER_REVERSE ? childCount - 1 - i : i;
+ final int result = ((LayoutParams) mDrawingOrderedChildren.get(index).getLayoutParams()).childIndex;
+ return result;
+ }
+
/**
* Set a separate OnPageChangeListener for internal use by the support library.
*
@@ -529,7 +778,7 @@ public class ViewPager extends ViewGroup {
*
* @param resId Resource ID of a drawable to display between pages
*/
- public void setPageMarginDrawable(int resId) {
+ public void setPageMarginDrawable(@DrawableRes int resId) {
setPageMarginDrawable(getContext().getResources().getDrawable(resId));
}
@@ -551,10 +800,10 @@ public class ViewPager extends ViewGroup {
// the screen has to travel, however, we don't want this duration to be effected in a
// purely linear fashion. Instead, we use this method to moderate the effect that the distance
// of travel has on the overall snap duration.
- static float distanceInfluenceForSnapDuration(float f) {
+ float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
- return (float)Math.sin((double)f);
+ return (float) Math.sin(f);
}
/**
@@ -585,16 +834,16 @@ public class ViewPager extends ViewGroup {
int dx = x - sx;
int dy = y - sy;
if (dx == 0 && dy == 0) {
- completeScroll();
+ completeScroll(false);
+ populate();
setScrollState(SCROLL_STATE_IDLE);
return;
}
setScrollingCacheEnabled(true);
- mScrolling = true;
setScrollState(SCROLL_STATE_SETTLING);
- final int width = getWidth();
+ final int width = getClientWidth();
final int halfWidth = width / 2;
final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width);
final float distance = halfWidth + halfWidth *
@@ -605,31 +854,37 @@ public class ViewPager extends ViewGroup {
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
- final float pageDelta = (float) Math.abs(dx) / (width + mPageMargin);
+ final float pageWidth = width * mAdapter.getPageWidth(mCurItem);
+ final float pageDelta = (float) Math.abs(dx) / (pageWidth + mPageMargin);
duration = (int) ((pageDelta + 1) * 100);
}
duration = Math.min(duration, MAX_SETTLE_DURATION);
mScroller.startScroll(sx, sy, dx, dy, duration);
- invalidate();
+ ViewCompat.postInvalidateOnAnimation(this);
}
- void addNewItem(int position, int index) {
+ ItemInfo addNewItem(int position, int index) {
ItemInfo ii = new ItemInfo();
ii.position = position;
ii.object = mAdapter.instantiateItem(this, position);
- if (index < 0) {
+ ii.widthFactor = mAdapter.getPageWidth(position);
+ if (index < 0 || index >= mItems.size()) {
mItems.add(ii);
} else {
mItems.add(index, ii);
}
+ return ii;
}
void dataSetChanged() {
// This method only gets called if our observer is attached, so mAdapter is non-null.
- boolean needPopulate = mItems.size() < 3 && mItems.size() < mAdapter.getCount();
- int newCurrItem = -1;
+ final int adapterCount = mAdapter.getCount();
+ mExpectedAdapterCount = adapterCount;
+ boolean needPopulate = mItems.size() < mOffscreenPageLimit * 2 + 1 &&
+ mItems.size() < adapterCount;
+ int newCurrItem = mCurItem;
boolean isUpdating = false;
for (int i = 0; i < mItems.size(); i++) {
@@ -654,7 +909,8 @@ public class ViewPager extends ViewGroup {
if (mCurItem == ii.position) {
// Keep the current item in the valid range
- newCurrItem = Math.max(0, Math.min(mCurItem, mAdapter.getCount() - 1));
+ newCurrItem = Math.max(0, Math.min(mCurItem, adapterCount - 1));
+ needPopulate = true;
}
continue;
}
@@ -676,19 +932,37 @@ public class ViewPager extends ViewGroup {
Collections.sort(mItems, COMPARATOR);
- if (newCurrItem >= 0) {
- // TODO This currently causes a jump.
- setCurrentItemInternal(newCurrItem, false, true);
- needPopulate = true;
- }
if (needPopulate) {
- populate();
+ // Reset our known page widths; populate will recompute them.
+ final int childCount = getChildCount();
+ for (int i = 0; i < childCount; i++) {
+ final View child = getChildAt(i);
+ final LayoutParams lp = (LayoutParams) child.getLayoutParams();
+ if (!lp.isDecor) {
+ lp.widthFactor = 0.f;
+ }
+ }
+
+ setCurrentItemInternal(newCurrItem, false, true);
requestLayout();
}
}
void populate() {
+ populate(mCurItem);
+ }
+
+ void populate(int newCurrentItem) {
+ ItemInfo oldCurInfo = null;
+ int focusDirection = View.FOCUS_FORWARD;
+ if (mCurItem != newCurrentItem) {
+ focusDirection = mCurItem < newCurrentItem ? View.FOCUS_RIGHT : View.FOCUS_LEFT;
+ oldCurInfo = infoForPosition(mCurItem);
+ mCurItem = newCurrentItem;
+ }
+
if (mAdapter == null) {
+ sortChildDrawingOrder();
return;
}
@@ -698,6 +972,7 @@ public class ViewPager extends ViewGroup {
// that position, avoiding glitches from happening at that point.
if (mPopulatePending) {
if (DEBUG) Log.i(TAG, "populate is pending, skipping for now...");
+ sortChildDrawingOrder();
return;
}
@@ -715,47 +990,110 @@ public class ViewPager extends ViewGroup {
final int N = mAdapter.getCount();
final int endPos = Math.min(N-1, mCurItem + pageLimit);
- if (DEBUG) Log.v(TAG, "populating: startPos=" + startPos + " endPos=" + endPos);
-
- // Add and remove pages in the existing list.
- int lastPos = -1;
- for (int i=0; i endPos) && !ii.scrolling) {
- if (DEBUG) Log.i(TAG, "removing: " + ii.position + " @ " + i);
- mItems.remove(i);
- i--;
- mAdapter.destroyItem(this, ii.position, ii.object);
- } else if (lastPos < endPos && ii.position > startPos) {
- // The next item is outside of our range, but we have a gap
- // between it and the last item where we want to have a page
- // shown. Fill in the gap.
- lastPos++;
- if (lastPos < startPos) {
- lastPos = startPos;
- }
- while (lastPos <= endPos && lastPos < ii.position) {
- if (DEBUG) Log.i(TAG, "inserting: " + lastPos + " @ " + i);
- addNewItem(lastPos, i);
- lastPos++;
- i++;
- }
+ if (N != mExpectedAdapterCount) {
+ String resName;
+ try {
+ resName = getResources().getResourceName(getId());
+ } catch (Resources.NotFoundException e) {
+ resName = Integer.toHexString(getId());
}
- lastPos = ii.position;
+ throw new IllegalStateException("The application's PagerAdapter changed the adapter's" +
+ " contents without calling PagerAdapter#notifyDataSetChanged!" +
+ " Expected adapter item count: " + mExpectedAdapterCount + ", found: " + N +
+ " Pager id: " + resName +
+ " Pager class: " + getClass() +
+ " Problematic adapter: " + mAdapter.getClass());
}
- // Add any new pages we need at the end.
- lastPos = mItems.size() > 0 ? mItems.get(mItems.size()-1).position : -1;
- if (lastPos < endPos) {
- lastPos++;
- lastPos = lastPos > startPos ? lastPos : startPos;
- while (lastPos <= endPos) {
- if (DEBUG) Log.i(TAG, "appending: " + lastPos);
- addNewItem(lastPos, -1);
- lastPos++;
+ // Locate the currently focused item or add it if needed.
+ int curIndex = -1;
+ ItemInfo curItem = null;
+ for (curIndex = 0; curIndex < mItems.size(); curIndex++) {
+ final ItemInfo ii = mItems.get(curIndex);
+ if (ii.position >= mCurItem) {
+ if (ii.position == mCurItem) curItem = ii;
+ break;
}
}
+ if (curItem == null && N > 0) {
+ curItem = addNewItem(mCurItem, curIndex);
+ }
+
+ // Fill 3x the available width or up to the number of offscreen
+ // pages requested to either side, whichever is larger.
+ // If we have no current item we have no work to do.
+ if (curItem != null) {
+ float extraWidthLeft = 0.f;
+ int itemIndex = curIndex - 1;
+ ItemInfo ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
+ final int clientWidth = getClientWidth();
+ final float leftWidthNeeded = clientWidth <= 0 ? 0 :
+ 2.f - curItem.widthFactor + (float) getPaddingLeft() / (float) clientWidth;
+ for (int pos = mCurItem - 1; pos >= 0; pos--) {
+ if (extraWidthLeft >= leftWidthNeeded && pos < startPos) {
+ if (ii == null) {
+ break;
+ }
+ if (pos == ii.position && !ii.scrolling) {
+ mItems.remove(itemIndex);
+ mAdapter.destroyItem(this, pos, ii.object);
+ if (DEBUG) {
+ Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
+ " view: " + ((View) ii.object));
+ }
+ itemIndex--;
+ curIndex--;
+ ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
+ }
+ } else if (ii != null && pos == ii.position) {
+ extraWidthLeft += ii.widthFactor;
+ itemIndex--;
+ ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
+ } else {
+ ii = addNewItem(pos, itemIndex + 1);
+ extraWidthLeft += ii.widthFactor;
+ curIndex++;
+ ii = itemIndex >= 0 ? mItems.get(itemIndex) : null;
+ }
+ }
+
+ float extraWidthRight = curItem.widthFactor;
+ itemIndex = curIndex + 1;
+ if (extraWidthRight < 2.f) {
+ ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
+ final float rightWidthNeeded = clientWidth <= 0 ? 0 :
+ (float) getPaddingRight() / (float) clientWidth + 2.f;
+ for (int pos = mCurItem + 1; pos < N; pos++) {
+ if (extraWidthRight >= rightWidthNeeded && pos > endPos) {
+ if (ii == null) {
+ break;
+ }
+ if (pos == ii.position && !ii.scrolling) {
+ mItems.remove(itemIndex);
+ mAdapter.destroyItem(this, pos, ii.object);
+ if (DEBUG) {
+ Log.i(TAG, "populate() - destroyItem() with pos: " + pos +
+ " view: " + ((View) ii.object));
+ }
+ ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
+ }
+ } else if (ii != null && pos == ii.position) {
+ extraWidthRight += ii.widthFactor;
+ itemIndex++;
+ ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
+ } else {
+ ii = addNewItem(pos, itemIndex);
+ itemIndex++;
+ extraWidthRight += ii.widthFactor;
+ ii = itemIndex < mItems.size() ? mItems.get(itemIndex) : null;
+ }
+ }
+ }
+
+ calculatePageOffsets(curItem, curIndex, oldCurInfo);
+ }
+
if (DEBUG) {
Log.i(TAG, "Current page list:");
for (int i=0; i();
+ } else {
+ mDrawingOrderedChildren.clear();
+ }
+ final int childCount = getChildCount();
+ for (int i = 0; i < childCount; i++) {
+ final View child = getChildAt(i);
+ mDrawingOrderedChildren.add(child);
+ }
+ Collections.sort(mDrawingOrderedChildren, sPositionComparator);
+ }
+ }
+
+ private void calculatePageOffsets(ItemInfo curItem, int curIndex, ItemInfo oldCurInfo) {
+ final int N = mAdapter.getCount();
+ final int width = getClientWidth();
+ final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
+ // Fix up offsets for later layout.
+ if (oldCurInfo != null) {
+ final int oldCurPosition = oldCurInfo.position;
+ // Base offsets off of oldCurInfo.
+ if (oldCurPosition < curItem.position) {
+ int itemIndex = 0;
+ ItemInfo ii = null;
+ float offset = oldCurInfo.offset + oldCurInfo.widthFactor + marginOffset;
+ for (int pos = oldCurPosition + 1;
+ pos <= curItem.position && itemIndex < mItems.size(); pos++) {
+ ii = mItems.get(itemIndex);
+ while (pos > ii.position && itemIndex < mItems.size() - 1) {
+ itemIndex++;
+ ii = mItems.get(itemIndex);
+ }
+ while (pos < ii.position) {
+ // We don't have an item populated for this,
+ // ask the adapter for an offset.
+ offset += mAdapter.getPageWidth(pos) + marginOffset;
+ pos++;
+ }
+ ii.offset = offset;
+ offset += ii.widthFactor + marginOffset;
+ }
+ } else if (oldCurPosition > curItem.position) {
+ int itemIndex = mItems.size() - 1;
+ ItemInfo ii = null;
+ float offset = oldCurInfo.offset;
+ for (int pos = oldCurPosition - 1;
+ pos >= curItem.position && itemIndex >= 0; pos--) {
+ ii = mItems.get(itemIndex);
+ while (pos < ii.position && itemIndex > 0) {
+ itemIndex--;
+ ii = mItems.get(itemIndex);
+ }
+ while (pos > ii.position) {
+ // We don't have an item populated for this,
+ // ask the adapter for an offset.
+ offset -= mAdapter.getPageWidth(pos) + marginOffset;
+ pos--;
+ }
+ offset -= ii.widthFactor + marginOffset;
+ ii.offset = offset;
+ }
+ }
+ }
+
+ // Base all offsets off of curItem.
+ final int itemCount = mItems.size();
+ float offset = curItem.offset;
+ int pos = curItem.position - 1;
+ mFirstOffset = curItem.position == 0 ? curItem.offset : -Float.MAX_VALUE;
+ mLastOffset = curItem.position == N - 1 ?
+ curItem.offset + curItem.widthFactor - 1 : Float.MAX_VALUE;
+ // Previous pages
+ for (int i = curIndex - 1; i >= 0; i--, pos--) {
+ final ItemInfo ii = mItems.get(i);
+ while (pos > ii.position) {
+ offset -= mAdapter.getPageWidth(pos--) + marginOffset;
+ }
+ offset -= ii.widthFactor + marginOffset;
+ ii.offset = offset;
+ if (ii.position == 0) mFirstOffset = offset;
+ }
+ offset = curItem.offset + curItem.widthFactor + marginOffset;
+ pos = curItem.position + 1;
+ // Next pages
+ for (int i = curIndex + 1; i < itemCount; i++, pos++) {
+ final ItemInfo ii = mItems.get(i);
+ while (pos < ii.position) {
+ offset += mAdapter.getPageWidth(pos++) + marginOffset;
+ }
+ if (ii.position == N - 1) {
+ mLastOffset = offset + ii.widthFactor - 1;
+ }
+ ii.offset = offset;
+ offset += ii.widthFactor + marginOffset;
+ }
+
+ mNeedCalculatePageOffsets = false;
+ }
+
/**
* This is the persistent state that is saved by ViewPager. Only needed
* if you are creating a sublass of ViewPager that must save its own
@@ -817,20 +1268,20 @@ public class ViewPager extends ViewGroup {
public String toString() {
return "FragmentPager.SavedState{"
+ Integer.toHexString(System.identityHashCode(this))
- + " position=" + position + '}';
+ + " position=" + position + "}";
}
public static final Parcelable.Creator CREATOR
- = new Parcelable.Creator() {
+ = ParcelableCompat.newCreator(new ParcelableCompatCreatorCallbacks() {
@Override
- public SavedState createFromParcel(Parcel in) {
- return new SavedState(in, null);
+ public SavedState createFromParcel(Parcel in, ClassLoader loader) {
+ return new SavedState(in, loader);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
- };
+ });
SavedState(Parcel in, ClassLoader loader) {
super(in);
@@ -885,8 +1336,8 @@ public class ViewPager extends ViewGroup {
if (lp != null && lp.isDecor) {
throw new IllegalStateException("Cannot add pager decor view during layout");
}
+ lp.needsMeasure = true;
addViewInLayout(child, index, params);
- child.measure(mChildWidthMeasureSpec, mChildHeightMeasureSpec);
} else {
super.addView(child, index, params);
}
@@ -900,6 +1351,15 @@ public class ViewPager extends ViewGroup {
}
}
+ @Override
+ public void removeView(View view) {
+ if (mInLayout) {
+ removeViewInLayout(view);
+ } else {
+ super.removeView(view);
+ }
+ }
+
ItemInfo infoForChild(View child) {
for (int i=0; i 0) {
- final int oldScrollPos = getScrollX();
- final int oldwwm = oldWidth + oldMargin;
- final int oldScrollItem = oldScrollPos / oldwwm;
- final float scrollOffset = (float) (oldScrollPos % oldwwm) / oldwwm;
- final int scrollPos = (int) ((oldScrollItem + scrollOffset) * widthWithMargin);
- scrollTo(scrollPos, getScrollY());
+ if (oldWidth > 0 && !mItems.isEmpty()) {
+ final int widthWithMargin = width - getPaddingLeft() - getPaddingRight() + margin;
+ final int oldWidthWithMargin = oldWidth - getPaddingLeft() - getPaddingRight()
+ + oldMargin;
+ final int xpos = getScrollX();
+ final float pageOffset = (float) xpos / oldWidthWithMargin;
+ final int newOffsetPixels = (int) (pageOffset * widthWithMargin);
+
+ scrollTo(newOffsetPixels, getScrollY());
if (!mScroller.isFinished()) {
// We now return to your regularly scheduled scroll, already in progress.
final int newDuration = mScroller.getDuration() - mScroller.timePassed();
- mScroller.startScroll(scrollPos, 0, mCurItem * widthWithMargin, 0, newDuration);
+ ItemInfo targetInfo = infoForPosition(mCurItem);
+ mScroller.startScroll(newOffsetPixels, 0,
+ (int) (targetInfo.offset * width), 0, newDuration);
}
} else {
- int scrollPos = mCurItem * widthWithMargin;
+ final ItemInfo ii = infoForPosition(mCurItem);
+ final float scrollOffset = ii != null ? Math.min(ii.offset, mLastOffset) : 0;
+ final int scrollPos = (int) (scrollOffset *
+ (width - getPaddingLeft() - getPaddingRight()));
if (scrollPos != getScrollX()) {
- completeScroll();
+ completeScroll(false);
scrollTo(scrollPos, getScrollY());
}
}
@@ -1038,10 +1533,6 @@ public class ViewPager extends ViewGroup {
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
- mInLayout = true;
- populate();
- mInLayout = false;
-
final int count = getChildCount();
int width = r - l;
int height = b - t;
@@ -1053,11 +1544,12 @@ public class ViewPager extends ViewGroup {
int decorCount = 0;
+ // First pass - decor views. We need to do this in two passes so that
+ // we have the proper offsets for non-decor views later.
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
- ItemInfo ii;
int childLeft = 0;
int childTop = 0;
if (lp.isDecor) {
@@ -1098,17 +1590,40 @@ public class ViewPager extends ViewGroup {
break;
}
childLeft += scrollX;
- decorCount++;
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
- } else if ((ii = infoForChild(child)) != null) {
- int loff = (width + mPageMargin) * ii.position;
- childLeft = paddingLeft + loff;
- childTop = paddingTop;
- if (DEBUG) Log.v(TAG, "Positioning #" + i + ' ' + child + " f=" + ii.object
- + ':' + childLeft + ',' + childTop + ' ' + child.getMeasuredWidth()
- + 'x' + child.getMeasuredHeight());
+ decorCount++;
+ }
+ }
+ }
+
+ final int childWidth = width - paddingLeft - paddingRight;
+ // Page views. Do this once we have the right padding offsets from above.
+ for (int i = 0; i < count; i++) {
+ final View child = getChildAt(i);
+ if (child.getVisibility() != GONE) {
+ final LayoutParams lp = (LayoutParams) child.getLayoutParams();
+ ItemInfo ii;
+ if (!lp.isDecor && (ii = infoForChild(child)) != null) {
+ int loff = (int) (childWidth * ii.offset);
+ int childLeft = paddingLeft + loff;
+ int childTop = paddingTop;
+ if (lp.needsMeasure) {
+ // This was added during layout and needs measurement.
+ // Do it now that we know what we're working with.
+ lp.needsMeasure = false;
+ final int widthSpec = MeasureSpec.makeMeasureSpec(
+ (int) (childWidth * lp.widthFactor),
+ MeasureSpec.EXACTLY);
+ final int heightSpec = MeasureSpec.makeMeasureSpec(
+ (int) (height - paddingTop - paddingBottom),
+ MeasureSpec.EXACTLY);
+ child.measure(widthSpec, heightSpec);
+ }
+ if (DEBUG) Log.v(TAG, "Positioning #" + i + " " + child + " f=" + ii.object
+ + ":" + childLeft + "," + childTop + " " + child.getMeasuredWidth()
+ + "x" + child.getMeasuredHeight());
child.layout(childLeft, childTop,
childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
@@ -1118,47 +1633,64 @@ public class ViewPager extends ViewGroup {
mTopPageBounds = paddingTop;
mBottomPageBounds = height - paddingBottom;
mDecorChildCount = decorCount;
+
+ if (mFirstLayout) {
+ scrollToItem(mCurItem, false, 0, false);
+ }
mFirstLayout = false;
}
@Override
public void computeScroll() {
- if (DEBUG) Log.i(TAG, "computeScroll: finished=" + mScroller.isFinished());
- if (!mScroller.isFinished()) {
- if (mScroller.computeScrollOffset()) {
- if (DEBUG) Log.i(TAG, "computeScroll: still scrolling");
- int oldX = getScrollX();
- int oldY = getScrollY();
- int x = mScroller.getCurrX();
- int y = mScroller.getCurrY();
+ if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
+ int oldX = getScrollX();
+ int oldY = getScrollY();
+ int x = mScroller.getCurrX();
+ int y = mScroller.getCurrY();
- if (oldX != x || oldY != y) {
- scrollTo(x, y);
- pageScrolled(x);
+ if (oldX != x || oldY != y) {
+ scrollTo(x, y);
+ if (!pageScrolled(x)) {
+ mScroller.abortAnimation();
+ scrollTo(0, y);
}
-
- // Keep on drawing until the animation has finished.
- invalidate();
- return;
}
+
+ // Keep on drawing until the animation has finished.
+ ViewCompat.postInvalidateOnAnimation(this);
+ return;
}
// Done with scroll, clean up state.
- completeScroll();
+ completeScroll(true);
}
- private void pageScrolled(int xpos) {
- final int widthWithMargin = getWidth() + mPageMargin;
- final int position = xpos / widthWithMargin;
- final int offsetPixels = xpos % widthWithMargin;
- final float offset = (float) offsetPixels / widthWithMargin;
+ private boolean pageScrolled(int xpos) {
+ if (mItems.size() == 0) {
+ mCalledSuper = false;
+ onPageScrolled(0, 0, 0);
+ if (!mCalledSuper) {
+ throw new IllegalStateException(
+ "onPageScrolled did not call superclass implementation");
+ }
+ return false;
+ }
+ final ItemInfo ii = infoForCurrentScrollPosition();
+ final int width = getClientWidth();
+ final int widthWithMargin = width + mPageMargin;
+ final float marginOffset = (float) mPageMargin / width;
+ final int currentPage = ii.position;
+ final float pageOffset = (((float) xpos / width) - ii.offset) /
+ (ii.widthFactor + marginOffset);
+ final int offsetPixels = (int) (pageOffset * widthWithMargin);
mCalledSuper = false;
- onPageScrolled(position, offset, offsetPixels);
+ onPageScrolled(currentPage, pageOffset, offsetPixels);
if (!mCalledSuper) {
throw new IllegalStateException(
"onPageScrolled did not call superclass implementation");
}
+ return true;
}
/**
@@ -1173,6 +1705,7 @@ public class ViewPager extends ViewGroup {
* @param offset Value from [0, 1) indicating the offset from the page at position.
* @param offsetPixels Value in pixels indicating the offset from position.
*/
+ @CallSuper
protected void onPageScrolled(int position, float offset, int offsetPixels) {
// Offset any decor views if needed - keep them on-screen at all times.
if (mDecorChildCount > 0) {
@@ -1214,17 +1747,78 @@ public class ViewPager extends ViewGroup {
}
}
+ dispatchOnPageScrolled(position, offset, offsetPixels);
+
+ if (mPageTransformer != null) {
+ final int scrollX = getScrollX();
+ final int childCount = getChildCount();
+ for (int i = 0; i < childCount; i++) {
+ final View child = getChildAt(i);
+ final LayoutParams lp = (LayoutParams) child.getLayoutParams();
+
+ if (lp.isDecor) continue;
+
+ final float transformPos = (float) (child.getLeft() - scrollX) / getClientWidth();
+ mPageTransformer.transformPage(child, transformPos);
+ }
+ }
+
+ mCalledSuper = true;
+ }
+
+ private void dispatchOnPageScrolled(int position, float offset, int offsetPixels) {
if (mOnPageChangeListener != null) {
mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
+ if (mOnPageChangeListeners != null) {
+ for (int i = 0, z = mOnPageChangeListeners.size(); i < z; i++) {
+ OnPageChangeListener listener = mOnPageChangeListeners.get(i);
+ if (listener != null) {
+ listener.onPageScrolled(position, offset, offsetPixels);
+ }
+ }
+ }
if (mInternalPageChangeListener != null) {
mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels);
}
- mCalledSuper = true;
}
- private void completeScroll() {
- boolean needPopulate = mScrolling;
+ private void dispatchOnPageSelected(int position) {
+ if (mOnPageChangeListener != null) {
+ mOnPageChangeListener.onPageSelected(position);
+ }
+ if (mOnPageChangeListeners != null) {
+ for (int i = 0, z = mOnPageChangeListeners.size(); i < z; i++) {
+ OnPageChangeListener listener = mOnPageChangeListeners.get(i);
+ if (listener != null) {
+ listener.onPageSelected(position);
+ }
+ }
+ }
+ if (mInternalPageChangeListener != null) {
+ mInternalPageChangeListener.onPageSelected(position);
+ }
+ }
+
+ private void dispatchOnScrollStateChanged(int state) {
+ if (mOnPageChangeListener != null) {
+ mOnPageChangeListener.onPageScrollStateChanged(state);
+ }
+ if (mOnPageChangeListeners != null) {
+ for (int i = 0, z = mOnPageChangeListeners.size(); i < z; i++) {
+ OnPageChangeListener listener = mOnPageChangeListeners.get(i);
+ if (listener != null) {
+ listener.onPageScrollStateChanged(state);
+ }
+ }
+ }
+ if (mInternalPageChangeListener != null) {
+ mInternalPageChangeListener.onPageScrollStateChanged(state);
+ }
+ }
+
+ private void completeScroll(boolean postEvents) {
+ boolean needPopulate = mScrollState == SCROLL_STATE_SETTLING;
if (needPopulate) {
// Done with scroll, no longer want to cache view drawing.
setScrollingCacheEnabled(false);
@@ -1235,11 +1829,12 @@ public class ViewPager extends ViewGroup {
int y = mScroller.getCurrY();
if (oldX != x || oldY != y) {
scrollTo(x, y);
+ if (x != oldX) {
+ pageScrolled(x);
+ }
}
- setScrollState(SCROLL_STATE_IDLE);
}
mPopulatePending = false;
- mScrolling = false;
for (int i=0; i 0) || (x > getWidth() - mGutterSize && dx < 0);
+ }
+
+ private void enableLayers(boolean enable) {
+ final int childCount = getChildCount();
+ for (int i = 0; i < childCount; i++) {
+ final int layerType = enable ?
+ ViewCompat.LAYER_TYPE_HARDWARE : ViewCompat.LAYER_TYPE_NONE;
+ ViewCompat.setLayerType(getChildAt(i), layerType, null);
}
}
@@ -1260,7 +1872,7 @@ public class ViewPager extends ViewGroup {
* scrolling there.
*/
- final int action = ev.getAction() & MotionEvent.ACTION_MASK;
+ final int action = ev.getAction() & MotionEventCompat.ACTION_MASK;
// Always take care of the touch gesture being complete.
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
@@ -1306,34 +1918,43 @@ public class ViewPager extends ViewGroup {
break;
}
- final int pointerIndex = ev.findPointerIndex( activePointerId);
- final float x = ev.getX(pointerIndex);
+ final int pointerIndex = MotionEventCompat.findPointerIndex(ev, activePointerId);
+ final float x = MotionEventCompat.getX(ev, pointerIndex);
final float dx = x - mLastMotionX;
final float xDiff = Math.abs(dx);
- final float y = ev.getY(pointerIndex);
- final float yDiff = Math.abs(y - mLastMotionY);
- if (DEBUG) Log.v(TAG, "Moved x to " + x + ',' + y + " diff=" + xDiff + ',' + yDiff);
+ final float y = MotionEventCompat.getY(ev, pointerIndex);
+ final float yDiff = Math.abs(y - mInitialMotionY);
+ if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
- if (canScroll(this, false, (int) dx, (int) x, (int) y)) {
+ if (dx != 0 && !isGutterDrag(mLastMotionX, dx) &&
+ canScroll(this, false, (int) dx, (int) x, (int) y)) {
// Nested view has scrollable area under this point. Let it be handled there.
- mInitialMotionX = mLastMotionX = x;
+ mLastMotionX = x;
mLastMotionY = y;
+ mIsUnableToDrag = true;
return false;
}
- if (xDiff > mTouchSlop && xDiff > yDiff) {
+ if (xDiff > mTouchSlop && xDiff * 0.5f > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
+ requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
- mLastMotionX = x;
+ mLastMotionX = dx > 0 ? mInitialMotionX + mTouchSlop :
+ mInitialMotionX - mTouchSlop;
+ mLastMotionY = y;
setScrollingCacheEnabled(true);
- } else {
- if (yDiff > mTouchSlop) {
- // The finger has moved enough in the vertical
- // direction to be counted as a drag... abort
- // any attempt to drag horizontally, to work correctly
- // with children that have scrolling containers.
- if (DEBUG) Log.v(TAG, "Starting unable to drag!");
- mIsUnableToDrag = true;
+ } else if (yDiff > mTouchSlop) {
+ // The finger has moved enough in the vertical
+ // direction to be counted as a drag... abort
+ // any attempt to drag horizontally, to work correctly
+ // with children that have scrolling containers.
+ if (DEBUG) Log.v(TAG, "Starting unable to drag!");
+ mIsUnableToDrag = true;
+ }
+ if (mIsBeingDragged) {
+ // Scroll to follow the motion event
+ if (performDrag(x)) {
+ ViewCompat.postInvalidateOnAnimation(this);
}
}
break;
@@ -1345,39 +1966,40 @@ public class ViewPager extends ViewGroup {
* ACTION_DOWN always refers to pointer index 0.
*/
mLastMotionX = mInitialMotionX = ev.getX();
- mLastMotionY = ev.getY();
- mActivePointerId = ev.getPointerId(0);
+ mLastMotionY = mInitialMotionY = ev.getY();
+ mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
+ mIsUnableToDrag = false;
- if (mScrollState == SCROLL_STATE_SETTLING) {
+ mScroller.computeScrollOffset();
+ if (mScrollState == SCROLL_STATE_SETTLING &&
+ Math.abs(mScroller.getFinalX() - mScroller.getCurrX()) > mCloseEnough) {
// Let the user 'catch' the pager as it animates.
+ mScroller.abortAnimation();
+ mPopulatePending = false;
+ populate();
mIsBeingDragged = true;
- mIsUnableToDrag = false;
+ requestParentDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
} else {
- completeScroll();
+ completeScroll(false);
mIsBeingDragged = false;
- mIsUnableToDrag = false;
}
- if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + ',' + mLastMotionY
+ if (DEBUG) Log.v(TAG, "Down at " + mLastMotionX + "," + mLastMotionY
+ " mIsBeingDragged=" + mIsBeingDragged
+ "mIsUnableToDrag=" + mIsUnableToDrag);
break;
}
- case MotionEvent.ACTION_POINTER_UP:
+ case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
break;
}
- if (!mIsBeingDragged) {
- // Track the velocity as long as we aren't dragging.
- // Once we start a real drag we will track in onTouchEvent.
- if (mVelocityTracker == null) {
- mVelocityTracker = VelocityTracker.obtain();
- }
- mVelocityTracker.addMovement(ev);
+ if (mVelocityTracker == null) {
+ mVelocityTracker = VelocityTracker.obtain();
}
+ mVelocityTracker.addMovement(ev);
/*
* The only time we want to intercept motion events is if we are in the
@@ -1414,89 +2036,67 @@ public class ViewPager extends ViewGroup {
final int action = ev.getAction();
boolean needsInvalidate = false;
- switch (action & MotionEvent.ACTION_MASK) {
+ switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
- /*
- * If being flinged and user touches, stop the fling. isFinished
- * will be false if being flinged.
- */
- completeScroll();
+ mScroller.abortAnimation();
+ mPopulatePending = false;
+ populate();
// Remember where the motion event started
mLastMotionX = mInitialMotionX = ev.getX();
- mActivePointerId = ev.getPointerId(0);
+ mLastMotionY = mInitialMotionY = ev.getY();
+ mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
break;
}
case MotionEvent.ACTION_MOVE:
if (!mIsBeingDragged) {
- final int pointerIndex = ev.findPointerIndex( mActivePointerId);
- final float x = ev.getX(pointerIndex);
+ final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
+ final float x = MotionEventCompat.getX(ev, pointerIndex);
final float xDiff = Math.abs(x - mLastMotionX);
- final float y = ev.getY(pointerIndex);
+ final float y = MotionEventCompat.getY(ev, pointerIndex);
final float yDiff = Math.abs(y - mLastMotionY);
- if (DEBUG) Log.v(TAG, "Moved x to " + x + ',' + y + " diff=" + xDiff + ',' + yDiff);
+ if (DEBUG) Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
if (xDiff > mTouchSlop && xDiff > yDiff) {
if (DEBUG) Log.v(TAG, "Starting drag!");
mIsBeingDragged = true;
- mLastMotionX = x;
+ requestParentDisallowInterceptTouchEvent(true);
+ mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop :
+ mInitialMotionX - mTouchSlop;
+ mLastMotionY = y;
setScrollState(SCROLL_STATE_DRAGGING);
setScrollingCacheEnabled(true);
+
+ // Disallow Parent Intercept, just in case
+ ViewParent parent = getParent();
+ if (parent != null) {
+ parent.requestDisallowInterceptTouchEvent(true);
+ }
}
}
+ // Not else! Note that mIsBeingDragged can be set above.
if (mIsBeingDragged) {
// Scroll to follow the motion event
- final int activePointerIndex = ev.findPointerIndex(
- mActivePointerId);
- final float x = ev.getX(activePointerIndex);
- final float deltaX = mLastMotionX - x;
- mLastMotionX = x;
- float oldScrollX = getScrollX();
- float scrollX = oldScrollX + deltaX;
- final int width = getWidth();
- final int widthWithMargin = width + mPageMargin;
-
- final int lastItemIndex = mAdapter.getCount() - 1;
- final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin);
- final float rightBound =
- Math.min(mCurItem + 1, lastItemIndex) * widthWithMargin;
- if (scrollX < leftBound) {
- if (leftBound == 0) {
- float over = -scrollX;
- if (Build.VERSION.SDK_INT >= 14) {
- mLeftEdge.onPull(over / width);
- }
- needsInvalidate = true;
- }
- scrollX = leftBound;
- } else if (scrollX > rightBound) {
- if (rightBound == lastItemIndex * widthWithMargin) {
- float over = scrollX - rightBound;
- if (Build.VERSION.SDK_INT >= 14) {
- mRightEdge.onPull(over / width);
- }
- needsInvalidate = true;
- }
- scrollX = rightBound;
- }
- // Don't lose the rounded component
- mLastMotionX += scrollX - (int) scrollX;
- scrollTo((int) scrollX, getScrollY());
- pageScrolled((int) scrollX);
+ final int activePointerIndex = MotionEventCompat.findPointerIndex(
+ ev, mActivePointerId);
+ final float x = MotionEventCompat.getX(ev, activePointerIndex);
+ needsInvalidate |= performDrag(x);
}
break;
case MotionEvent.ACTION_UP:
if (mIsBeingDragged) {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
- int initialVelocity = (int)velocityTracker.getXVelocity(mActivePointerId);
+ int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
+ velocityTracker, mActivePointerId);
mPopulatePending = true;
- final int widthWithMargin = getWidth() + mPageMargin;
+ final int width = getClientWidth();
final int scrollX = getScrollX();
- final int currentPage = scrollX / widthWithMargin;
- final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin;
+ final ItemInfo ii = infoForCurrentScrollPosition();
+ final int currentPage = ii.position;
+ final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
final int activePointerIndex =
- ev.findPointerIndex( mActivePointerId);
- final float x = ev.getX(activePointerIndex);
+ MotionEventCompat.findPointerIndex(ev, mActivePointerId);
+ final float x = MotionEventCompat.getX(ev, activePointerIndex);
final int totalDelta = (int) (x - mInitialMotionX);
int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
totalDelta);
@@ -1504,50 +2104,151 @@ public class ViewPager extends ViewGroup {
mActivePointerId = INVALID_POINTER;
endDrag();
- if (Build.VERSION.SDK_INT >= 14) {
- mLeftEdge.onRelease();
- mRightEdge.onRelease();
- needsInvalidate = mLeftEdge.isFinished() || mRightEdge.isFinished();
- }
+ needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
}
break;
case MotionEvent.ACTION_CANCEL:
if (mIsBeingDragged) {
- setCurrentItemInternal(mCurItem, true, true);
+ scrollToItem(mCurItem, true, 0, false);
mActivePointerId = INVALID_POINTER;
endDrag();
- if (Build.VERSION.SDK_INT >= 14) {
- mLeftEdge.onRelease();
- mRightEdge.onRelease();
- needsInvalidate = mLeftEdge.isFinished() || mRightEdge.isFinished();
- }
+ needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
}
break;
- case MotionEvent.ACTION_POINTER_DOWN: {
- final int index = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
- final float x = ev.getX(index);
+ case MotionEventCompat.ACTION_POINTER_DOWN: {
+ final int index = MotionEventCompat.getActionIndex(ev);
+ final float x = MotionEventCompat.getX(ev, index);
mLastMotionX = x;
- mActivePointerId = ev.getPointerId(index);
+ mActivePointerId = MotionEventCompat.getPointerId(ev, index);
break;
}
- case MotionEvent.ACTION_POINTER_UP:
+ case MotionEventCompat.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
- mLastMotionX = ev.getX(
- ev.findPointerIndex( mActivePointerId));
+ mLastMotionX = MotionEventCompat.getX(ev,
+ MotionEventCompat.findPointerIndex(ev, mActivePointerId));
break;
}
if (needsInvalidate) {
- invalidate();
+ ViewCompat.postInvalidateOnAnimation(this);
}
return true;
}
+ private void requestParentDisallowInterceptTouchEvent(boolean disallowIntercept) {
+ final ViewParent parent = getParent();
+ if (parent != null) {
+ parent.requestDisallowInterceptTouchEvent(disallowIntercept);
+ }
+ }
+
+ private boolean performDrag(float x) {
+ boolean needsInvalidate = false;
+
+ final float deltaX = mLastMotionX - x;
+ mLastMotionX = x;
+
+ float oldScrollX = getScrollX();
+ float scrollX = oldScrollX + deltaX;
+ final int width = getClientWidth();
+
+ float leftBound = width * mFirstOffset;
+ float rightBound = width * mLastOffset;
+ boolean leftAbsolute = true;
+ boolean rightAbsolute = true;
+
+ final ItemInfo firstItem = mItems.get(0);
+ final ItemInfo lastItem = mItems.get(mItems.size() - 1);
+ if (firstItem.position != 0) {
+ leftAbsolute = false;
+ leftBound = firstItem.offset * width;
+ }
+ if (lastItem.position != mAdapter.getCount() - 1) {
+ rightAbsolute = false;
+ rightBound = lastItem.offset * width;
+ }
+
+ if (scrollX < leftBound) {
+ if (leftAbsolute) {
+ float over = leftBound - scrollX;
+ needsInvalidate = mLeftEdge.onPull(Math.abs(over) / width);
+ }
+ scrollX = leftBound;
+ } else if (scrollX > rightBound) {
+ if (rightAbsolute) {
+ float over = scrollX - rightBound;
+ needsInvalidate = mRightEdge.onPull(Math.abs(over) / width);
+ }
+ scrollX = rightBound;
+ }
+ // Don't lose the rounded component
+ mLastMotionX += scrollX - (int) scrollX;
+ scrollTo((int) scrollX, getScrollY());
+ pageScrolled((int) scrollX);
+
+ return needsInvalidate;
+ }
+
+ /**
+ * @return Info about the page at the current scroll position.
+ * This can be synthetic for a missing middle page; the 'object' field can be null.
+ */
+ private ItemInfo infoForCurrentScrollPosition() {
+ final int width = getClientWidth();
+ final float scrollOffset = width > 0 ? (float) getScrollX() / width : 0;
+ final float marginOffset = width > 0 ? (float) mPageMargin / width : 0;
+ int lastPos = -1;
+ float lastOffset = 0.f;
+ float lastWidth = 0.f;
+ boolean first = true;
+
+ ItemInfo lastItem = null;
+ for (int i = 0; i < mItems.size(); i++) {
+ ItemInfo ii = mItems.get(i);
+ float offset;
+ if (!first && ii.position != lastPos + 1) {
+ // Create a synthetic item for a missing page.
+ ii = mTempItem;
+ ii.offset = lastOffset + lastWidth + marginOffset;
+ ii.position = lastPos + 1;
+ ii.widthFactor = mAdapter.getPageWidth(ii.position);
+ i--;
+ }
+ offset = ii.offset;
+
+ final float leftBound = offset;
+ final float rightBound = offset + ii.widthFactor + marginOffset;
+ if (first || scrollOffset >= leftBound) {
+ if (scrollOffset < rightBound || i == mItems.size() - 1) {
+ return ii;
+ }
+ } else {
+ return lastItem;
+ }
+ first = false;
+ lastPos = ii.position;
+ lastOffset = offset;
+ lastWidth = ii.widthFactor;
+ lastItem = ii;
+ }
+
+ return lastItem;
+ }
+
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 {
- targetPage = (int) (currentPage + pageOffset + 0.5f);
+ final float truncator = currentPage >= mCurItem ? 0.4f : 0.6f;
+ targetPage = (int) (currentPage + pageOffset + truncator);
+ }
+
+ if (mItems.size() > 0) {
+ final ItemInfo firstItem = mItems.get(0);
+ final ItemInfo lastItem = mItems.get(mItems.size() - 1);
+
+ // Only let the user target pages we have items for
+ targetPage = Math.max(firstItem.position, Math.min(targetPage, lastItem.position));
}
return targetPage;
@@ -1556,46 +2257,42 @@ public class ViewPager extends ViewGroup {
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
+ boolean needsInvalidate = false;
- if (Build.VERSION.SDK_INT >= 14) {
- boolean needsInvalidate = false;
+ final int overScrollMode = ViewCompat.getOverScrollMode(this);
+ if (overScrollMode == ViewCompat.OVER_SCROLL_ALWAYS ||
+ (overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS &&
+ mAdapter != null && mAdapter.getCount() > 1)) {
+ if (!mLeftEdge.isFinished()) {
+ final int restoreCount = canvas.save();
+ final int height = getHeight() - getPaddingTop() - getPaddingBottom();
+ final int width = getWidth();
- final int overScrollMode = this.getOverScrollMode();
- if (overScrollMode == View.OVER_SCROLL_ALWAYS ||
- (overScrollMode == View.OVER_SCROLL_IF_CONTENT_SCROLLS &&
- mAdapter != null && mAdapter.getCount() > 1)) {
- if (!mLeftEdge.isFinished()) {
- final int restoreCount = canvas.save();
- final int height = getHeight() - getPaddingTop() - getPaddingBottom();
-
- canvas.rotate(270);
- canvas.translate(-height + getPaddingTop(), 0);
- mLeftEdge.setSize(height, getWidth());
- needsInvalidate |= mLeftEdge.draw(canvas);
- canvas.restoreToCount(restoreCount);
- }
- if (!mRightEdge.isFinished()) {
- final int restoreCount = canvas.save();
- final int width = getWidth();
- final int height = getHeight() - getPaddingTop() - getPaddingBottom();
- final int itemCount = mAdapter != null ? mAdapter.getCount() : 1;
-
- canvas.rotate(90);
- canvas.translate(-getPaddingTop(),
- -itemCount * (width + mPageMargin) + mPageMargin);
- mRightEdge.setSize(height, width);
- needsInvalidate |= mRightEdge.draw(canvas);
- canvas.restoreToCount(restoreCount);
- }
- } else {
- mLeftEdge.finish();
- mRightEdge.finish();
+ canvas.rotate(270);
+ canvas.translate(-height + getPaddingTop(), mFirstOffset * width);
+ mLeftEdge.setSize(height, width);
+ needsInvalidate |= mLeftEdge.draw(canvas);
+ canvas.restoreToCount(restoreCount);
}
+ if (!mRightEdge.isFinished()) {
+ final int restoreCount = canvas.save();
+ final int width = getWidth();
+ final int height = getHeight() - getPaddingTop() - getPaddingBottom();
- if (needsInvalidate) {
- // Keep animating
- invalidate();
+ canvas.rotate(90);
+ canvas.translate(-getPaddingTop(), -(mLastOffset + 1) * width);
+ mRightEdge.setSize(height, width);
+ needsInvalidate |= mRightEdge.draw(canvas);
+ canvas.restoreToCount(restoreCount);
}
+ } else {
+ mLeftEdge.finish();
+ mRightEdge.finish();
+ }
+
+ if (needsInvalidate) {
+ // Keep animating
+ ViewCompat.postInvalidateOnAnimation(this);
}
}
@@ -1603,17 +2300,42 @@ public class ViewPager extends ViewGroup {
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
- // Draw the margin drawable if needed.
- if (mPageMargin > 0 && mMarginDrawable != null) {
+ // Draw the margin drawable between pages if needed.
+ if (mPageMargin > 0 && mMarginDrawable != null && mItems.size() > 0 && mAdapter != null) {
final int scrollX = getScrollX();
final int width = getWidth();
- final int offset = scrollX % (width + mPageMargin);
- if (offset != 0) {
- // Pages fit completely when settled; we only need to draw when in between
- final int left = scrollX - offset + width;
- mMarginDrawable.setBounds(left, mTopPageBounds, left + mPageMargin,
- mBottomPageBounds);
- mMarginDrawable.draw(canvas);
+
+ final float marginOffset = (float) mPageMargin / width;
+ int itemIndex = 0;
+ ItemInfo ii = mItems.get(0);
+ float offset = ii.offset;
+ final int itemCount = mItems.size();
+ final int firstPos = ii.position;
+ final int lastPos = mItems.get(itemCount - 1).position;
+ for (int pos = firstPos; pos < lastPos; pos++) {
+ while (pos > ii.position && itemIndex < itemCount) {
+ ii = mItems.get(++itemIndex);
+ }
+
+ float drawAt;
+ if (pos == ii.position) {
+ drawAt = (ii.offset + ii.widthFactor) * width;
+ offset = ii.offset + ii.widthFactor + marginOffset;
+ } else {
+ float widthFactor = mAdapter.getPageWidth(pos);
+ drawAt = (offset + widthFactor) * width;
+ offset += widthFactor + marginOffset;
+ }
+
+ if (drawAt + mPageMargin > scrollX) {
+ mMarginDrawable.setBounds((int) drawAt, mTopPageBounds,
+ (int) (drawAt + mPageMargin + 0.5f), mBottomPageBounds);
+ mMarginDrawable.draw(canvas);
+ }
+
+ if (drawAt > scrollX + width) {
+ break; // No more visible, no sense in continuing
+ }
}
}
}
@@ -1668,14 +2390,17 @@ public class ViewPager extends ViewGroup {
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
- int initialVelocity = (int)velocityTracker.getYVelocity(mActivePointerId);
+ int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(
+ velocityTracker, mActivePointerId);
mPopulatePending = true;
- final int totalDelta = (int) (mLastMotionX - mInitialMotionX);
+ final int width = getClientWidth();
final int scrollX = getScrollX();
- final int widthWithMargin = getWidth() + mPageMargin;
- final int currentPage = scrollX / widthWithMargin;
- final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin;
- int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta);
+ final ItemInfo ii = infoForCurrentScrollPosition();
+ final int currentPage = ii.position;
+ final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
+ final int totalDelta = (int) (mLastMotionX - mInitialMotionX);
+ int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity,
+ totalDelta);
setCurrentItemInternal(nextPage, true, true, initialVelocity);
endDrag();
@@ -1695,13 +2420,23 @@ public class ViewPager extends ViewGroup {
}
mLastMotionX += xOffset;
- float scrollX = getScrollX() - xOffset;
- final int width = getWidth();
- final int widthWithMargin = width + mPageMargin;
- final float leftBound = Math.max(0, (mCurItem - 1) * widthWithMargin);
- final float rightBound =
- Math.min(mCurItem + 1, mAdapter.getCount() - 1) * widthWithMargin;
+ float oldScrollX = getScrollX();
+ float scrollX = oldScrollX - xOffset;
+ final int width = getClientWidth();
+
+ float leftBound = width * mFirstOffset;
+ float rightBound = width * mLastOffset;
+
+ final ItemInfo firstItem = mItems.get(0);
+ final ItemInfo lastItem = mItems.get(mItems.size() - 1);
+ if (firstItem.position != 0) {
+ leftBound = firstItem.offset * width;
+ }
+ if (lastItem.position != mAdapter.getCount() - 1) {
+ rightBound = lastItem.offset * width;
+ }
+
if (scrollX < leftBound) {
scrollX = leftBound;
} else if (scrollX > rightBound) {
@@ -1734,14 +2469,14 @@ public class ViewPager extends ViewGroup {
}
private void onSecondaryPointerUp(MotionEvent ev) {
- final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
- final int pointerId = ev.getPointerId(pointerIndex);
+ final int pointerIndex = MotionEventCompat.getActionIndex(ev);
+ final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
- mLastMotionX = ev.getX(newPointerIndex);
- mActivePointerId = ev.getPointerId(newPointerIndex);
+ mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex);
+ mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
if (mVelocityTracker != null) {
mVelocityTracker.clear();
}
@@ -1773,6 +2508,22 @@ public class ViewPager extends ViewGroup {
}
}
+ public boolean canScrollHorizontally(int direction) {
+ if (mAdapter == null) {
+ return false;
+ }
+
+ final int width = getClientWidth();
+ final int scrollX = getScrollX();
+ if (direction < 0) {
+ return (scrollX > (int) (width * mFirstOffset));
+ } else if (direction > 0) {
+ return (scrollX < (int) (width * mLastOffset));
+ } else {
+ return false;
+ }
+ }
+
/**
* Tests scrollability within child views of v given a delta of dx.
*
@@ -1784,7 +2535,7 @@ public class ViewPager extends ViewGroup {
* @param y Y coordinate of the active touch point
* @return true if child views of v can be scrolled by delta of dx.
*/
- protected static boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
+ protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewGroup) {
final ViewGroup group = (ViewGroup) v;
final int scrollX = v.getScrollX();
@@ -1804,11 +2555,7 @@ public class ViewPager extends ViewGroup {
}
}
- if (Build.VERSION.SDK_INT >= 14) {
- return checkV && v.canScrollHorizontally(-dx);
- } else {
- return false;
- }
+ return checkV && ViewCompat.canScrollHorizontally(v, -dx);
}
@Override
@@ -1839,9 +2586,9 @@ public class ViewPager extends ViewGroup {
if (Build.VERSION.SDK_INT >= 11) {
// The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD
// before Android 3.0. Ignore the tab key on those devices.
- if (CompatHoneycomb.hasNoModifiers(event)) {
+ if (KeyEventCompat.hasNoModifiers(event)) {
handled = arrowScroll(FOCUS_FORWARD);
- } else if (CompatHoneycomb.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
+ } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
handled = arrowScroll(FOCUS_BACKWARD);
}
}
@@ -1853,7 +2600,30 @@ public class ViewPager extends ViewGroup {
public boolean arrowScroll(int direction) {
View currentFocused = findFocus();
- if (currentFocused == this) currentFocused = null;
+ if (currentFocused == this) {
+ currentFocused = null;
+ } else if (currentFocused != null) {
+ boolean isChild = false;
+ for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
+ parent = parent.getParent()) {
+ if (parent == this) {
+ isChild = true;
+ break;
+ }
+ }
+ if (!isChild) {
+ // This would cause the focus search down below to fail in fun ways.
+ final StringBuilder sb = new StringBuilder();
+ sb.append(currentFocused.getClass().getSimpleName());
+ for (ViewParent parent = currentFocused.getParent(); parent instanceof ViewGroup;
+ parent = parent.getParent()) {
+ sb.append(" => ").append(parent.getClass().getSimpleName());
+ }
+ Log.e(TAG, "arrowScroll tried to find focus based on non-child " +
+ "current focused view " + sb.toString());
+ currentFocused = null;
+ }
+ }
boolean handled = false;
@@ -1863,7 +2633,9 @@ public class ViewPager extends ViewGroup {
if (direction == View.FOCUS_LEFT) {
// If there is nothing to the left, or this is causing us to
// jump to the right, then what we really want to do is page left.
- if (currentFocused != null && nextFocused.getLeft() >= currentFocused.getLeft()) {
+ final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
+ final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
+ if (currentFocused != null && nextLeft >= currLeft) {
handled = pageLeft();
} else {
handled = nextFocused.requestFocus();
@@ -1871,7 +2643,9 @@ public class ViewPager extends ViewGroup {
} else if (direction == View.FOCUS_RIGHT) {
// If there is nothing to the right, or this is causing us to
// jump to the left, then what we really want to do is page right.
- if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) {
+ final int nextLeft = getChildRectInPagerCoordinates(mTempRect, nextFocused).left;
+ final int currLeft = getChildRectInPagerCoordinates(mTempRect, currentFocused).left;
+ if (currentFocused != null && nextLeft <= currLeft) {
handled = pageRight();
} else {
handled = nextFocused.requestFocus();
@@ -1890,6 +2664,32 @@ public class ViewPager extends ViewGroup {
return handled;
}
+ private Rect getChildRectInPagerCoordinates(Rect outRect, View child) {
+ if (outRect == null) {
+ outRect = new Rect();
+ }
+ if (child == null) {
+ outRect.set(0, 0, 0, 0);
+ return outRect;
+ }
+ outRect.left = child.getLeft();
+ outRect.right = child.getRight();
+ outRect.top = child.getTop();
+ outRect.bottom = child.getBottom();
+
+ ViewParent parent = child.getParent();
+ while (parent instanceof ViewGroup && parent != this) {
+ final ViewGroup group = (ViewGroup) parent;
+ outRect.left += group.getLeft();
+ outRect.right += group.getRight();
+ outRect.top += group.getTop();
+ outRect.bottom += group.getBottom();
+
+ parent = group.getParent();
+ }
+ return outRect;
+ }
+
boolean pageLeft() {
if (mCurItem > 0) {
setCurrentItem(mCurItem-1, true);
@@ -2004,11 +2804,12 @@ public class ViewPager extends ViewGroup {
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
- // ViewPagers should only report accessibility info for the current page,
- // otherwise things get very confusing.
-
- // TODO: Should this note something about the paging container?
+ // Dispatch scroll events from this ViewPager.
+ if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED) {
+ return super.dispatchPopulateAccessibilityEvent(event);
+ }
+ // Dispatch all other accessibility events from the current page.
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
@@ -2044,6 +2845,62 @@ public class ViewPager extends ViewGroup {
return new LayoutParams(getContext(), attrs);
}
+ class MyAccessibilityDelegate extends AccessibilityDelegateCompat {
+
+ @Override
+ public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) {
+ super.onInitializeAccessibilityEvent(host, event);
+ event.setClassName(ViewPager.class.getName());
+ final AccessibilityRecordCompat recordCompat = AccessibilityRecordCompat.obtain();
+ recordCompat.setScrollable(canScroll());
+ if (event.getEventType() == AccessibilityEventCompat.TYPE_VIEW_SCROLLED
+ && mAdapter != null) {
+ recordCompat.setItemCount(mAdapter.getCount());
+ recordCompat.setFromIndex(mCurItem);
+ recordCompat.setToIndex(mCurItem);
+ }
+ }
+
+ @Override
+ public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
+ super.onInitializeAccessibilityNodeInfo(host, info);
+ info.setClassName(ViewPager.class.getName());
+ info.setScrollable(canScroll());
+ if (canScrollHorizontally(1)) {
+ info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
+ }
+ if (canScrollHorizontally(-1)) {
+ info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
+ }
+ }
+
+ @Override
+ public boolean performAccessibilityAction(View host, int action, Bundle args) {
+ if (super.performAccessibilityAction(host, action, args)) {
+ return true;
+ }
+ switch (action) {
+ case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: {
+ if (canScrollHorizontally(1)) {
+ setCurrentItem(mCurItem + 1);
+ return true;
+ }
+ } return false;
+ case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: {
+ if (canScrollHorizontally(-1)) {
+ setCurrentItem(mCurItem - 1);
+ return true;
+ }
+ } return false;
+ }
+ return false;
+ }
+
+ private boolean canScroll() {
+ return (mAdapter != null) && (mAdapter.getCount() > 1);
+ }
+ }
+
private class PagerObserver extends DataSetObserver {
@Override
public void onChanged() {
@@ -2067,21 +2924,55 @@ public class ViewPager extends ViewGroup {
public boolean isDecor;
/**
+ * Gravity setting for use on decor views only:
* Where to position the view page within the overall ViewPager
* container; constants are defined in {@link android.view.Gravity}.
*/
public int gravity;
+ /**
+ * Width as a 0-1 multiplier of the measured pager width
+ */
+ float widthFactor = 0.f;
+
+ /**
+ * true if this view was added during layout and needs to be measured
+ * before being positioned.
+ */
+ boolean needsMeasure;
+
+ /**
+ * Adapter position this view is for if !isDecor
+ */
+ int position;
+
+ /**
+ * Current child index within the ViewPager that this view occupies
+ */
+ int childIndex;
+
public LayoutParams() {
- super(MATCH_PARENT, MATCH_PARENT);
+ super(FILL_PARENT, FILL_PARENT);
}
public LayoutParams(Context context, AttributeSet attrs) {
super(context, attrs);
final TypedArray a = context.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
- gravity = a.getInteger(0, Gravity.NO_GRAVITY);
+ gravity = a.getInteger(0, Gravity.TOP);
a.recycle();
}
}
+
+ static class ViewPositionComparator implements Comparator {
+ @Override
+ public int compare(View lhs, View rhs) {
+ final LayoutParams llp = (LayoutParams) lhs.getLayoutParams();
+ final LayoutParams rlp = (LayoutParams) rhs.getLayoutParams();
+ if (llp.isDecor != rlp.isDecor) {
+ return llp.isDecor ? 1 : -1;
+ }
+ return llp.position - rlp.position;
+ }
+ }
}