blob: cc9a075828284c3b93cee46df80a08d7f9398b9c [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen7d30a372013-07-01 17:03:59 -070027import android.content.res.Resources;
Adam Cohen9c4949e2010-10-05 12:27:22 -070028import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070029import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070030import android.graphics.Matrix;
31import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070032import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070033import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070034import android.os.Parcel;
35import android.os.Parcelable;
36import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070047import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070048import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070049import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070050import android.view.animation.AnimationUtils;
51import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080052import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070053import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070054import android.widget.Scroller;
55
Winson Chung6a0f57d2011-06-29 20:10:49 -070056import java.util.ArrayList;
57
Winson Chung321e9ee2010-08-09 13:37:56 -070058/**
59 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070060 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070061 */
Michael Jurka8b805b12012-04-18 14:23:14 -070062public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070063 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070064 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070065 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070066
Winson Chung86f77532010-08-24 11:08:22 -070067 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070068 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070069
Adam Cohen7d30a372013-07-01 17:03:59 -070070 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070071 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070072 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070073
Adam Cohenb5ba0972011-09-07 18:02:31 -070074 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070075 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080076
Adam Cohenb64cb5a2011-02-15 13:53:42 -080077 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080078 // The page is moved more than halfway, automatically move to the next page on touch up.
79 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080080
Adam Cohen265b9a62011-12-07 14:37:18 -080081 // The following constants need to be scaled based on density. The scaled versions will be
82 // assigned to the corresponding member variables below.
83 private static final int FLING_THRESHOLD_VELOCITY = 500;
84 private static final int MIN_SNAP_VELOCITY = 1500;
85 private static final int MIN_FLING_VELOCITY = 250;
86
Adam Cohen7d30a372013-07-01 17:03:59 -070087 // We are disabling touch interaction of the widget region for factory ROM.
88 private static final boolean DISABLE_TOUCH_INTERACTION = false;
89 private static final boolean DISABLE_TOUCH_SIDE_PAGES = false;
Adam Cohendedbd962013-07-11 14:21:49 -070090 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070091
Winson Chung8aad6102012-05-11 16:27:49 -070092 static final int AUTOMATIC_PAGE_SPACING = -1;
93
Adam Cohen265b9a62011-12-07 14:37:18 -080094 protected int mFlingThresholdVelocity;
95 protected int mMinFlingVelocity;
96 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -070097
Adam Cohenb5ba0972011-09-07 18:02:31 -070098 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -070099 protected float mSmoothingTime;
100 protected float mTouchX;
101
102 protected boolean mFirstLayout = true;
103
104 protected int mCurrentPage;
Adam Cohene61a9a22013-06-11 15:45:31 -0700105 protected int mChildCountOnLastMeasure;
106
Michael Jurka0142d492010-08-25 17:46:15 -0700107 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800108 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700109 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700110 private VelocityTracker mVelocityTracker;
111
Adam Cohen7d30a372013-07-01 17:03:59 -0700112 private float mParentDownMotionX;
113 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700114 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700115 private float mDownMotionY;
116 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800117 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800118 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800119 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800120 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700121 private int mLastScreenCenter = -1;
Adam Cohen73894962011-10-31 13:17:17 -0700122 private int[] mChildOffsets;
123 private int[] mChildRelativeOffsets;
124 private int[] mChildOffsetsWithLayoutScale;
Winson Chung321e9ee2010-08-09 13:37:56 -0700125
Michael Jurka0142d492010-08-25 17:46:15 -0700126 protected final static int TOUCH_STATE_REST = 0;
127 protected final static int TOUCH_STATE_SCROLLING = 1;
128 protected final static int TOUCH_STATE_PREV_PAGE = 2;
129 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700130 protected final static int TOUCH_STATE_REORDERING = 4;
131
Adam Cohene45440e2010-10-14 18:33:38 -0700132 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700133
Michael Jurka0142d492010-08-25 17:46:15 -0700134 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700135 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700136
Michael Jurka0142d492010-08-25 17:46:15 -0700137 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700138
Michael Jurka7426c422010-11-11 15:23:47 -0800139 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140 private int mPagingTouchSlop;
141 private int mMaximumVelocity;
Winson Chung1908d072011-02-24 18:09:44 -0800142 private int mMinimumWidth;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700143 protected int mPageSpacing;
144 protected int mPageLayoutPaddingTop;
145 protected int mPageLayoutPaddingBottom;
146 protected int mPageLayoutPaddingLeft;
147 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700148 protected int mPageLayoutWidthGap;
149 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700150 protected int mCellCountX = 0;
151 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700152 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800153 protected boolean mAllowOverScroll = true;
154 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800155 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700156 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700157
Michael Jurka8b805b12012-04-18 14:23:14 -0700158 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800159 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
160 // the screens from continuing to translate beyond the normal bounds.
161 protected int mOverScrollX;
162
Michael Jurka8c920dd2011-01-20 14:16:56 -0800163 // parameter that adjusts the layout to be optimized for pages with that scale factor
Michael Jurkad3ef3062010-11-23 16:23:58 -0800164 protected float mLayoutScale = 1.0f;
165
Michael Jurka5f1c5092010-09-03 14:15:02 -0700166 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700167
Michael Jurka5f1c5092010-09-03 14:15:02 -0700168 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700169
Winson Chung86f77532010-08-24 11:08:22 -0700170 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurkae326f182011-11-21 14:05:46 -0800172 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700173
Michael Jurka0142d492010-08-25 17:46:15 -0700174 // If true, syncPages and syncPageItems will be called to refresh pages
175 protected boolean mContentIsRefreshable = true;
176
177 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700178 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700179
180 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
181 // to switch to a new page
182 protected boolean mUsePagingTouchSlop = true;
183
Michael Jurka8b805b12012-04-18 14:23:14 -0700184 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700185 // (SmoothPagedView does this)
186 protected boolean mDeferScrollUpdate = false;
187
Patrick Dubroy1262e362010-10-06 15:49:50 -0700188 protected boolean mIsPageMoving = false;
189
Winson Chungf0ea4d32011-06-06 14:27:16 -0700190 // All syncs and layout passes are deferred until data is ready.
191 protected boolean mIsDataReady = false;
192
Adam Cohen7d30a372013-07-01 17:03:59 -0700193 protected boolean mAllowLongPress = true;
194
Winson Chung007c6982011-06-14 13:27:53 -0700195 // Scrolling indicator
Winson Chungbb6f6a52011-07-25 17:55:44 -0700196 private ValueAnimator mScrollIndicatorAnimator;
Michael Jurkaafaa0502011-12-13 18:22:50 -0800197 private View mScrollIndicator;
Winson Chungf5f8cef2011-07-22 11:16:13 -0700198 private int mScrollIndicatorPaddingLeft;
199 private int mScrollIndicatorPaddingRight;
Winson Chung007c6982011-06-14 13:27:53 -0700200 private boolean mHasScrollIndicator = true;
Michael Jurkabed61d22012-02-14 22:51:29 -0800201 private boolean mShouldShowScrollIndicator = false;
202 private boolean mShouldShowScrollIndicatorImmediately = false;
Winson Chunga6427b12011-07-27 10:53:39 -0700203 protected static final int sScrollIndicatorFadeInDuration = 150;
204 protected static final int sScrollIndicatorFadeOutDuration = 650;
205 protected static final int sScrollIndicatorFlashDuration = 650;
Chet Haasebc2f0822012-10-26 17:59:53 -0700206 private boolean mScrollingPaused = false;
Winson Chung007c6982011-06-14 13:27:53 -0700207
Adam Cohen7d30a372013-07-01 17:03:59 -0700208 // The viewport whether the pages are to be contained (the actual view may be larger than the
209 // viewport)
210 private Rect mViewport = new Rect();
211
212 // Reordering
213 // We use the min scale to determine how much to expand the actually PagedView measured
214 // dimensions such that when we are zoomed out, the view is not clipped
215 private int REORDERING_DROP_REPOSITION_DURATION = 200;
216 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
217 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
218 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
219 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
220 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
221 private float mMinScale = 1f;
222 protected View mDragView;
223 protected AnimatorSet mZoomInOutAnim;
224 private Runnable mSidePageHoverRunnable;
225 private int mSidePageHoverIndex = -1;
226 // This variable's scope is only for the duration of startReordering() and endReordering()
227 private boolean mReorderingStarted = false;
228 // This variable's scope is for the duration of startReordering() and after the zoomIn()
229 // animation after endReordering()
230 private boolean mIsReordering;
231 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
232 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
233 private int mPostReorderingPreZoomInRemainingAnimationCount;
234 private Runnable mPostReorderingPreZoomInRunnable;
235
236 // Edge swiping
237 private boolean mOnlyAllowEdgeSwipes = false;
238 private boolean mDownEventOnEdge = false;
239 private int mEdgeSwipeRegionSize = 0;
240
241 // Convenience/caching
242 private Matrix mTmpInvMatrix = new Matrix();
243 private float[] mTmpPoint = new float[2];
244 private Rect mTmpRect = new Rect();
245 private Rect mAltTmpRect = new Rect();
246
247 // Fling to delete
248 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
249 private float FLING_TO_DELETE_FRICTION = 0.035f;
250 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
251 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
252 protected int mFlingToDeleteThresholdVelocity = -1400;
253 // Drag to delete
254 private boolean mDeferringForDelete = false;
255 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
256 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
257
258 // Drop to delete
259 private View mDeleteDropTarget;
260
261 private boolean mAutoComputePageSpacing = false;
262 private boolean mRecomputePageSpacing = false;
263
264 // Bouncer
265 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700266
Winson Chung86f77532010-08-24 11:08:22 -0700267 public interface PageSwitchListener {
268 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700269 }
270
Winson Chung321e9ee2010-08-09 13:37:56 -0700271 public PagedView(Context context) {
272 this(context, null);
273 }
274
275 public PagedView(Context context, AttributeSet attrs) {
276 this(context, attrs, 0);
277 }
278
279 public PagedView(Context context, AttributeSet attrs, int defStyle) {
280 super(context, attrs, defStyle);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 TypedArray a = context.obtainStyledAttributes(attrs,
282 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800283 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700284 if (mPageSpacing < 0) {
285 mAutoComputePageSpacing = mRecomputePageSpacing = true;
286 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700287 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800288 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700289 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800290 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800292 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700293 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800294 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700295 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700296 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700297 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700298 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungf5f8cef2011-07-22 11:16:13 -0700299 mScrollIndicatorPaddingLeft =
300 a.getDimensionPixelSize(R.styleable.PagedView_scrollIndicatorPaddingLeft, 0);
301 mScrollIndicatorPaddingRight =
302 a.getDimensionPixelSize(R.styleable.PagedView_scrollIndicatorPaddingRight, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700303 a.recycle();
304
Winson Chung321e9ee2010-08-09 13:37:56 -0700305 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700306 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700307 }
308
309 /**
310 * Initializes various states for this workspace.
311 */
Michael Jurka0142d492010-08-25 17:46:15 -0700312 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700313 mDirtyPageContent = new ArrayList<Boolean>();
314 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800315 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700316 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700317 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700318
319 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700320 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700321 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
322 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700323 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800324
Adam Cohen7d30a372013-07-01 17:03:59 -0700325 // Scale the fling-to-delete threshold by the density
326 mFlingToDeleteThresholdVelocity =
327 (int) (mFlingToDeleteThresholdVelocity * mDensity);
328
Adam Cohen265b9a62011-12-07 14:37:18 -0800329 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
330 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
331 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700332 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700333 }
334
Adam Cohen7d30a372013-07-01 17:03:59 -0700335 void setDeleteDropTarget(View v) {
336 mDeleteDropTarget = v;
337 }
338
339 // Convenience methods to map points from self to parent and vice versa
340 float[] mapPointFromViewToParent(View v, float x, float y) {
341 mTmpPoint[0] = x;
342 mTmpPoint[1] = y;
343 v.getMatrix().mapPoints(mTmpPoint);
344 mTmpPoint[0] += v.getLeft();
345 mTmpPoint[1] += v.getTop();
346 return mTmpPoint;
347 }
348 float[] mapPointFromParentToView(View v, float x, float y) {
349 mTmpPoint[0] = x - v.getLeft();
350 mTmpPoint[1] = y - v.getTop();
351 v.getMatrix().invert(mTmpInvMatrix);
352 mTmpInvMatrix.mapPoints(mTmpPoint);
353 return mTmpPoint;
354 }
355
356 void updateDragViewTranslationDuringDrag() {
357 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
358 float y = mLastMotionY - mDownMotionY;
359 mDragView.setTranslationX(x);
360 mDragView.setTranslationY(y);
361
362 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
363 }
364
365 public void setMinScale(float f) {
366 mMinScale = f;
367 requestLayout();
368 }
369
370 @Override
371 public void setScaleX(float scaleX) {
372 super.setScaleX(scaleX);
373 if (isReordering(true)) {
374 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
375 mLastMotionX = p[0];
376 mLastMotionY = p[1];
377 updateDragViewTranslationDuringDrag();
378 }
379 }
380
381 // Convenience methods to get the actual width/height of the PagedView (since it is measured
382 // to be larger to account for the minimum possible scale)
383 int getViewportWidth() {
384 return mViewport.width();
385 }
386 int getViewportHeight() {
387 return mViewport.height();
388 }
389
390 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
391 // PagedView both horizontally and vertically
392 int getViewportOffsetX() {
393 return (getMeasuredWidth() - getViewportWidth()) / 2;
394 }
395
396 int getViewportOffsetY() {
397 return (getMeasuredHeight() - getViewportHeight()) / 2;
398 }
399
Winson Chung86f77532010-08-24 11:08:22 -0700400 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
401 mPageSwitchListener = pageSwitchListener;
402 if (mPageSwitchListener != null) {
403 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700404 }
405 }
406
407 /**
Winson Chung52aee602013-01-30 12:01:02 -0800408 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
409 */
410 public boolean isLayoutRtl() {
411 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
412 }
413
414 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700415 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
416 * out pages.
417 */
418 protected void setDataIsReady() {
419 mIsDataReady = true;
420 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700421
Winson Chungf0ea4d32011-06-06 14:27:16 -0700422 protected boolean isDataReady() {
423 return mIsDataReady;
424 }
425
426 /**
Winson Chung86f77532010-08-24 11:08:22 -0700427 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700428 *
Winson Chung86f77532010-08-24 11:08:22 -0700429 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700430 */
Winson Chung86f77532010-08-24 11:08:22 -0700431 int getCurrentPage() {
432 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700433 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700434
Winson Chung360e63f2012-04-27 13:48:05 -0700435 int getNextPage() {
436 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
437 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700438
Winson Chung86f77532010-08-24 11:08:22 -0700439 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700440 return getChildCount();
441 }
442
Winson Chung86f77532010-08-24 11:08:22 -0700443 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700444 return getChildAt(index);
445 }
446
Adam Cohenae4f1552011-10-20 00:15:42 -0700447 protected int indexToPage(int index) {
448 return index;
449 }
450
Winson Chung321e9ee2010-08-09 13:37:56 -0700451 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800452 * Updates the scroll of the current page immediately to its final scroll position. We use this
453 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
454 * the previous tab page.
455 */
456 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700457 // If the current page is invalid, just reset the scroll position to zero
458 int newX = 0;
459 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
460 int offset = getChildOffset(mCurrentPage);
461 int relOffset = getRelativeChildOffset(mCurrentPage);
462 newX = offset - relOffset;
463 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800464 scrollTo(newX, 0);
465 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800466 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800467 }
468
469 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700470 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
471 * ends, {@link #resumeScrolling()} should be called, along with
472 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
473 */
474 void pauseScrolling() {
475 mScroller.forceFinished(true);
476 cancelScrollingIndicatorAnimations();
477 mScrollingPaused = true;
478 }
479
480 /**
481 * Enables scrolling again.
482 * @see #pauseScrolling()
483 */
484 void resumeScrolling() {
485 mScrollingPaused = false;
486 }
487 /**
Winson Chung86f77532010-08-24 11:08:22 -0700488 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700489 */
Winson Chung86f77532010-08-24 11:08:22 -0700490 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800491 if (!mScroller.isFinished()) {
492 mScroller.abortAnimation();
493 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800494 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
495 // the default
496 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800497 return;
498 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700499
Adam Cohene61a9a22013-06-11 15:45:31 -0700500 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700501 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chungbbc60d82010-11-11 16:34:41 -0800502 updateCurrentPageScroll();
Winson Chung5a808352011-06-27 19:08:49 -0700503 updateScrollingIndicator();
Winson Chung86f77532010-08-24 11:08:22 -0700504 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800505 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700506 }
507
Michael Jurka0142d492010-08-25 17:46:15 -0700508 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700509 if (mPageSwitchListener != null) {
510 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700511 }
512 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800513 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700514 if (!mIsPageMoving) {
515 mIsPageMoving = true;
516 onPageBeginMoving();
517 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700518 }
519
Michael Jurkace7e05f2011-02-01 22:02:35 -0800520 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700521 if (mIsPageMoving) {
522 mIsPageMoving = false;
523 onPageEndMoving();
524 }
Michael Jurka0142d492010-08-25 17:46:15 -0700525 }
526
Adam Cohen26976d92011-03-22 15:33:33 -0700527 protected boolean isPageMoving() {
528 return mIsPageMoving;
529 }
530
Michael Jurka0142d492010-08-25 17:46:15 -0700531 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700532 protected void onPageBeginMoving() {
533 }
534
535 // a method that subclasses can override to add behavior
536 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700537 }
538
Winson Chung321e9ee2010-08-09 13:37:56 -0700539 /**
Winson Chung86f77532010-08-24 11:08:22 -0700540 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700541 *
542 * @param l The listener used to respond to long clicks.
543 */
544 @Override
545 public void setOnLongClickListener(OnLongClickListener l) {
546 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700547 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700548 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700549 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700550 }
551 }
552
553 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800554 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700555 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800556 }
557
558 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700559 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700560 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800561 mUnboundedScrollX = x;
562
Adam Cohen0ffac432013-07-10 11:19:26 -0700563 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
564 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
565 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800566 super.scrollTo(0, y);
567 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700568 if (isRtl) {
569 overScroll(x - mMaxScrollX);
570 } else {
571 overScroll(x);
572 }
Adam Cohen68d73932010-11-15 10:50:58 -0800573 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700574 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800575 super.scrollTo(mMaxScrollX, y);
576 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700577 if (isRtl) {
578 overScroll(x);
579 } else {
580 overScroll(x - mMaxScrollX);
581 }
Adam Cohen68d73932010-11-15 10:50:58 -0800582 }
583 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800584 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800585 super.scrollTo(x, y);
586 }
587
Michael Jurka0142d492010-08-25 17:46:15 -0700588 mTouchX = x;
589 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700590
591 // Update the last motion events when scrolling
592 if (isReordering(true)) {
593 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
594 mLastMotionX = p[0];
595 mLastMotionY = p[1];
596 updateDragViewTranslationDuringDrag();
597 }
Michael Jurka0142d492010-08-25 17:46:15 -0700598 }
599
600 // we moved this functionality to a helper function so SmoothPagedView can reuse it
601 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700602 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700603 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700604 if (getScrollX() != mScroller.getCurrX()
605 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700606 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700607 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
608 }
Michael Jurka0142d492010-08-25 17:46:15 -0700609 invalidate();
610 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700611 } else if (mNextPage != INVALID_PAGE) {
612 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700613 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700614 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700615
Adam Cohen73aa9752010-11-24 16:26:58 -0800616 // We don't want to trigger a page end moving unless the page has settled
617 // and the user has stopped scrolling
618 if (mTouchState == TOUCH_STATE_REST) {
619 pageEndMoving();
620 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700621
Adam Cohen7d30a372013-07-01 17:03:59 -0700622 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700623 // Notify the user when the page changes
624 AccessibilityManager accessibilityManager = (AccessibilityManager)
625 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
626 if (accessibilityManager.isEnabled()) {
627 AccessibilityEvent ev =
628 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
629 ev.getText().add(getCurrentPageDescription());
630 sendAccessibilityEventUnchecked(ev);
631 }
Michael Jurka0142d492010-08-25 17:46:15 -0700632 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700633 }
Michael Jurka0142d492010-08-25 17:46:15 -0700634 return false;
635 }
636
637 @Override
638 public void computeScroll() {
639 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700640 }
641
Adam Cohen7d30a372013-07-01 17:03:59 -0700642 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
643 return mTopAlignPageWhenShrinkingForBouncer;
644 }
645
Winson Chung321e9ee2010-08-09 13:37:56 -0700646 @Override
647 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700648 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700649 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
650 return;
651 }
652
Adam Cohen7d30a372013-07-01 17:03:59 -0700653 // We measure the dimensions of the PagedView to be larger than the pages so that when we
654 // zoom out (and scale down), the view is still contained in the parent
655 View parent = (View) getParent();
656 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
657 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
658 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700659 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700660 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
661 // viewport, we can be at most one and a half screens offset once we scale down
662 DisplayMetrics dm = getResources().getDisplayMetrics();
663 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
664 int parentWidthSize = (int) (1.5f * maxSize);
665 int parentHeightSize = maxSize;
666 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
667 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
668 mViewport.set(0, 0, widthSize, heightSize);
669
670 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
671 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
672 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700673 }
674
Winson Chung8aad6102012-05-11 16:27:49 -0700675 // Return early if we aren't given a proper dimension
676 if (widthSize <= 0 || heightSize <= 0) {
677 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
678 return;
679 }
680
Adam Lesinski6b879f02010-11-04 16:15:23 -0700681 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
682 * of the All apps view on XLarge displays to not take up more space then it needs. Width
683 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
684 * each page to have the same width.
685 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700686 final int verticalPadding = getPaddingTop() + getPaddingBottom();
687 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700688
689 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700690 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700691 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700692 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
693 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
694 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
695 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700696 final int childCount = getChildCount();
697 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700698 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700699 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700700 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
701
702 int childWidthMode;
703 if (lp.width == LayoutParams.WRAP_CONTENT) {
704 childWidthMode = MeasureSpec.AT_MOST;
705 } else {
706 childWidthMode = MeasureSpec.EXACTLY;
707 }
708
709 int childHeightMode;
710 if (lp.height == LayoutParams.WRAP_CONTENT) {
711 childHeightMode = MeasureSpec.AT_MOST;
712 } else {
713 childHeightMode = MeasureSpec.EXACTLY;
714 }
715
716 final int childWidthMeasureSpec =
Winson Chungea359c62011-08-03 17:06:35 -0700717 MeasureSpec.makeMeasureSpec(widthSize - horizontalPadding, childWidthMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700718 final int childHeightMeasureSpec =
Adam Lesinski6b879f02010-11-04 16:15:23 -0700719 MeasureSpec.makeMeasureSpec(heightSize - verticalPadding, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700720
721 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700722 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700723 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700724
Winson Chung8aad6102012-05-11 16:27:49 -0700725 // We can't call getChildOffset/getRelativeChildOffset until we set the measured dimensions.
726 // We also wait until we set the measured dimensions before flushing the cache as well, to
727 // ensure that the cache is filled with good values.
728 invalidateCachedOffsets();
729
Adam Cohen7d30a372013-07-01 17:03:59 -0700730 if (mChildCountOnLastMeasure != getChildCount() && !mDeferringForDelete) {
Adam Cohene61a9a22013-06-11 15:45:31 -0700731 setCurrentPage(mCurrentPage);
732 }
733 mChildCountOnLastMeasure = getChildCount();
734
Winson Chunga128a7b2012-04-30 15:23:15 -0700735 if (childCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700736 if (DEBUG) Log.d(TAG, "getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chunga128a7b2012-04-30 15:23:15 -0700737 + getChildWidth(0));
738
739 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700740 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700741 // The gap between pages in the PagedView should be equal to the gap from the page
742 // to the edge of the screen (so it is not visible in the current screen). To
743 // account for unequal padding on each side of the paged view, we take the maximum
744 // of the left/right gap and use that as the gap between each page.
745 int offset = getRelativeChildOffset(0);
746 int spacing = Math.max(offset, widthSize - offset -
747 getChildAt(0).getMeasuredWidth());
748 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700749 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700750 }
751 }
752
Adam Cohen25b29952011-11-02 14:49:06 -0700753 updateScrollingIndicatorPosition();
754
Adam Cohenfaa28302010-11-19 12:02:18 -0800755 if (childCount > 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700756 final int index = isLayoutRtl() ? 0 : childCount - 1;
757 mMaxScrollX = getChildOffset(index) - getRelativeChildOffset(index);
Adam Cohenfaa28302010-11-19 12:02:18 -0800758 } else {
759 mMaxScrollX = 0;
760 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700761 }
762
Adam Cohen60b07122011-11-14 17:26:06 -0800763 public void setPageSpacing(int pageSpacing) {
764 mPageSpacing = pageSpacing;
765 invalidateCachedOffsets();
766 }
767
Winson Chung321e9ee2010-08-09 13:37:56 -0700768 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700769 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700771 return;
772 }
773
Winson Chung785d2eb2011-04-14 16:08:02 -0700774 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700775 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700776
Adam Cohen7d30a372013-07-01 17:03:59 -0700777 int offsetX = getViewportOffsetX();
778 int offsetY = getViewportOffsetY();
779
780 // Update the viewport offsets
781 mViewport.offset(offsetX, offsetY);
782
Adam Cohen0ffac432013-07-10 11:19:26 -0700783 final boolean isRtl = isLayoutRtl();
784
785 final int startIndex = isRtl ? childCount - 1 : 0;
786 final int endIndex = isRtl ? -1 : childCount;
787 final int delta = isRtl ? -1 : 1;
788
Adam Cohen7d30a372013-07-01 17:03:59 -0700789 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohen0ffac432013-07-10 11:19:26 -0700790 int childLeft = offsetX + getRelativeChildOffset(startIndex);
791 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700792 final View child = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -0700793 int childTop = offsetY + getPaddingTop();
794 if (mCenterPagesVertically) {
795 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
796 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700797 if (child.getVisibility() != View.GONE) {
Michael Jurkad3ef3062010-11-23 16:23:58 -0800798 final int childWidth = getScaledMeasuredWidth(child);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700799 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800800
Winson Chung785d2eb2011-04-14 16:08:02 -0700801 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700802 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800803 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700804 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700805 }
806 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700807
808 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
809 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800810 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700811 setHorizontalScrollBarEnabled(true);
812 mFirstLayout = false;
813 }
Winson Chunge3193b92010-09-10 11:44:42 -0700814 }
815
Adam Cohenf34bab52010-09-30 14:11:56 -0700816 protected void screenScrolled(int screenCenter) {
Adam Cohen73894962011-10-31 13:17:17 -0700817 if (isScrollingIndicatorEnabled()) {
818 updateScrollingIndicator();
819 }
Michael Jurka869390b2012-05-06 15:55:19 -0700820 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
821
822 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700823 for (int i = 0; i < getChildCount(); i++) {
824 View child = getChildAt(i);
825 if (child != null) {
826 float scrollProgress = getScrollProgress(screenCenter, child, i);
827 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800828 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700829 }
830 }
831 invalidate();
832 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700833 }
834
Winson Chunge3193b92010-09-10 11:44:42 -0700835 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700836 public void onChildViewAdded(View parent, View child) {
Adam Cohen2591f6a2011-10-25 14:36:40 -0700837 // This ensures that when children are added, they get the correct transforms / alphas
838 // in accordance with any scroll effects.
839 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700840 mRecomputePageSpacing = true;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700841 invalidate();
Adam Cohen25b29952011-11-02 14:49:06 -0700842 invalidateCachedOffsets();
Adam Cohen2591f6a2011-10-25 14:36:40 -0700843 }
844
Michael Jurka8b805b12012-04-18 14:23:14 -0700845 @Override
846 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700847 mForceScreenScrolled = true;
848 invalidate();
849 invalidateCachedOffsets();
Michael Jurka8b805b12012-04-18 14:23:14 -0700850 }
851
Adam Cohen73894962011-10-31 13:17:17 -0700852 protected void invalidateCachedOffsets() {
853 int count = getChildCount();
Adam Cohen25b29952011-11-02 14:49:06 -0700854 if (count == 0) {
855 mChildOffsets = null;
856 mChildRelativeOffsets = null;
857 mChildOffsetsWithLayoutScale = null;
858 return;
859 }
Adam Cohen73894962011-10-31 13:17:17 -0700860
861 mChildOffsets = new int[count];
862 mChildRelativeOffsets = new int[count];
863 mChildOffsetsWithLayoutScale = new int[count];
864 for (int i = 0; i < count; i++) {
865 mChildOffsets[i] = -1;
866 mChildRelativeOffsets[i] = -1;
867 mChildOffsetsWithLayoutScale[i] = -1;
868 }
869 }
870
871 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700872 if (index < 0 || index > getChildCount() - 1) return 0;
873
Adam Cohen0ffac432013-07-10 11:19:26 -0700874 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700875 int[] childOffsets = Float.compare(mLayoutScale, 1f) == 0 ?
876 mChildOffsets : mChildOffsetsWithLayoutScale;
877
878 if (childOffsets != null && childOffsets[index] != -1) {
879 return childOffsets[index];
880 } else {
881 if (getChildCount() == 0)
882 return 0;
883
Adam Cohen0ffac432013-07-10 11:19:26 -0700884
885 final int startIndex = isRtl ? getChildCount() - 1 : 0;
886 final int endIndex = isRtl ? index : index;
887 final int delta = isRtl ? -1 : 1;
888
889 int offset = getRelativeChildOffset(startIndex);
890 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen73894962011-10-31 13:17:17 -0700891 offset += getScaledMeasuredWidth(getPageAt(i)) + mPageSpacing;
892 }
893 if (childOffsets != null) {
894 childOffsets[index] = offset;
895 }
896 return offset;
897 }
898 }
899
900 protected int getRelativeChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700901 if (index < 0 || index > getChildCount() - 1) return 0;
902
Adam Cohen73894962011-10-31 13:17:17 -0700903 if (mChildRelativeOffsets != null && mChildRelativeOffsets[index] != -1) {
904 return mChildRelativeOffsets[index];
905 } else {
Michael Jurka8b805b12012-04-18 14:23:14 -0700906 final int padding = getPaddingLeft() + getPaddingRight();
907 final int offset = getPaddingLeft() +
Adam Cohen7d30a372013-07-01 17:03:59 -0700908 (getViewportWidth() - padding - getChildWidth(index)) / 2;
Adam Cohen73894962011-10-31 13:17:17 -0700909 if (mChildRelativeOffsets != null) {
910 mChildRelativeOffsets[index] = offset;
911 }
912 return offset;
913 }
914 }
915
Adam Cohen73894962011-10-31 13:17:17 -0700916 protected int getScaledMeasuredWidth(View child) {
917 // This functions are called enough times that it actually makes a difference in the
918 // profiler -- so just inline the max() here
919 final int measuredWidth = child.getMeasuredWidth();
920 final int minWidth = mMinimumWidth;
921 final int maxWidth = (minWidth > measuredWidth) ? minWidth : measuredWidth;
922 return (int) (maxWidth * mLayoutScale + 0.5f);
923 }
924
Adam Cohen7d30a372013-07-01 17:03:59 -0700925 void boundByReorderablePages(boolean isReordering, int[] range) {
926 // Do nothing
927 }
928
929 // TODO: Fix this
Michael Jurkadde558b2011-11-09 22:09:06 -0800930 protected void getVisiblePages(int[] range) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700931 range[0] = 0;
932 range[1] = getPageCount() - 1;
933
934 /*
Michael Jurka0142d492010-08-25 17:46:15 -0700935 final int pageCount = getChildCount();
Michael Jurka4ff7d792012-04-02 03:46:50 -0700936
Michael Jurkac4fb9172010-09-02 17:19:20 -0700937 if (pageCount > 0) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700938 final int screenWidth = getViewportWidth();
939 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700940 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700941 int offsetX = getViewportOffsetX() + getScrollX();
Michael Jurka47f74742012-03-02 13:39:13 -0800942 View currPage = getPageAt(leftScreen);
Adam Cohen7d30a372013-07-01 17:03:59 -0700943 while (leftScreen < pageCount - 1 &&
Michael Jurka8b805b12012-04-18 14:23:14 -0700944 currPage.getX() + currPage.getWidth() -
Adam Cohen7d30a372013-07-01 17:03:59 -0700945 currPage.getPaddingRight() < offsetX) {
946 leftScreen++;
Michael Jurka47f74742012-03-02 13:39:13 -0800947 currPage = getPageAt(leftScreen);
Michael Jurkac4fb9172010-09-02 17:19:20 -0700948 }
949 rightScreen = leftScreen;
Adam Cohen7d30a372013-07-01 17:03:59 -0700950 currPage = getPageAt(rightScreen + 1);
951 while (rightScreen < pageCount - 1 &&
952 currPage.getX() - currPage.getPaddingLeft() < offsetX + screenWidth) {
953 rightScreen++;
954 currPage = getPageAt(rightScreen + 1);
Michael Jurkac4fb9172010-09-02 17:19:20 -0700955 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700956
957 // TEMP: this is a hacky way to ensure that animations to new pages are not clipped
958 // because we don't draw them while scrolling?
959 range[0] = Math.max(0, leftScreen - 1);
960 range[1] = Math.min(rightScreen + 1, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -0800961 } else {
962 range[0] = -1;
963 range[1] = -1;
964 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700965 */
Michael Jurkadde558b2011-11-09 22:09:06 -0800966 }
967
Michael Jurka920d7f42012-05-14 16:29:55 -0700968 protected boolean shouldDrawChild(View child) {
969 return child.getAlpha() > 0;
970 }
971
Michael Jurkadde558b2011-11-09 22:09:06 -0800972 @Override
973 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700974 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -0700975 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
976 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -0800977 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -0800978
979 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -0700980 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
981 // set it for the next frame
982 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -0800983 screenScrolled(screenCenter);
984 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -0800985 }
986
987 // Find out which screens are visible; as an optimization we only call draw on them
988 final int pageCount = getChildCount();
989 if (pageCount > 0) {
990 getVisiblePages(mTempVisiblePagesRange);
991 final int leftScreen = mTempVisiblePagesRange[0];
992 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -0800993 if (leftScreen != -1 && rightScreen != -1) {
994 final long drawingTime = getDrawingTime();
995 // Clip to the bounds
996 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -0700997 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
998 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -0700999
Adam Cohen7d30a372013-07-01 17:03:59 -07001000 // Draw all the children, leaving the drag view for last
1001 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001002 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001003 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001004 if (mForceDrawAllChildrenNextFrame ||
1005 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001006 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001007 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001008 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001009 // Draw the drag view on top (if there is one)
1010 if (mDragView != null) {
1011 drawChild(canvas, mDragView, drawingTime);
1012 }
1013
Michael Jurka5e368ff2012-05-14 23:13:15 -07001014 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001015 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001016 }
Michael Jurka0142d492010-08-25 17:46:15 -07001017 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001018 }
1019
1020 @Override
1021 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001022 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001023 if (page != mCurrentPage || !mScroller.isFinished()) {
1024 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001025 return true;
1026 }
1027 return false;
1028 }
1029
1030 @Override
1031 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001032 int focusablePage;
1033 if (mNextPage != INVALID_PAGE) {
1034 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001035 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001036 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001037 }
Winson Chung86f77532010-08-24 11:08:22 -07001038 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001039 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001040 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001041 }
1042 return false;
1043 }
1044
1045 @Override
1046 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001047 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001048 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001049 if (getCurrentPage() > 0) {
1050 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001051 return true;
1052 }
1053 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001054 if (getCurrentPage() < getPageCount() - 1) {
1055 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001056 return true;
1057 }
1058 }
1059 return super.dispatchUnhandledMove(focused, direction);
1060 }
1061
1062 @Override
1063 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001064 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001065 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001066 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001067 }
1068 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001069 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001070 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001071 }
1072 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001073 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001074 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001075 }
1076 }
1077 }
1078
1079 /**
1080 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001081 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001082 *
Winson Chung86f77532010-08-24 11:08:22 -07001083 * This happens when live folders requery, and if they're off page, they
1084 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001085 */
1086 @Override
1087 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001088 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001089 View v = focused;
1090 while (true) {
1091 if (v == current) {
1092 super.focusableViewAvailable(focused);
1093 return;
1094 }
1095 if (v == this) {
1096 return;
1097 }
1098 ViewParent parent = v.getParent();
1099 if (parent instanceof View) {
1100 v = (View)v.getParent();
1101 } else {
1102 return;
1103 }
1104 }
1105 }
1106
1107 /**
1108 * {@inheritDoc}
1109 */
1110 @Override
1111 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1112 if (disallowIntercept) {
1113 // We need to make sure to cancel our long press if
1114 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001115 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001116 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001117 }
1118 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1119 }
1120
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001121 /**
1122 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1123 */
1124 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001125 if (isLayoutRtl()) {
1126 return (x > (getViewportOffsetX() + getViewportWidth() -
1127 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
1128 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001129 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001130 }
1131
1132 /**
1133 * Return true if a tap at (x, y) should trigger a flip to the next page.
1134 */
1135 protected boolean hitsNextPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001136 if (isLayoutRtl()) {
1137 return (x < getViewportOffsetX() + getRelativeChildOffset(mCurrentPage) - mPageSpacing);
1138 }
1139 return (x > (getViewportOffsetX() + getViewportWidth() -
1140 getRelativeChildOffset(mCurrentPage) + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001141 }
Winson Chung52aee602013-01-30 12:01:02 -08001142
Adam Cohen7d30a372013-07-01 17:03:59 -07001143 /** Returns whether x and y originated within the buffered viewport */
1144 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1145 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1146 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1147 return mTmpRect.contains(x, y);
1148 }
1149
1150 /** Returns whether x and y originated within the current page view bounds */
1151 private boolean isTouchPointInCurrentPage(int x, int y) {
1152 View v = getPageAt(getCurrentPage());
1153 if (v != null) {
1154 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1155 v.getBottom());
1156 return mTmpRect.contains(x, y);
1157 }
1158 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001159 }
1160
Winson Chung321e9ee2010-08-09 13:37:56 -07001161 @Override
1162 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001163 if (DISABLE_TOUCH_INTERACTION) {
1164 return false;
1165 }
1166
Winson Chung321e9ee2010-08-09 13:37:56 -07001167 /*
1168 * This method JUST determines whether we want to intercept the motion.
1169 * If we return true, onTouchEvent will be called and we do the actual
1170 * scrolling there.
1171 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001172 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001173
Winson Chung45e1d6e2010-11-09 17:19:49 -08001174 // Skip touch handling if there are no pages to swipe
1175 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1176
Winson Chung321e9ee2010-08-09 13:37:56 -07001177 /*
1178 * Shortcut the most recurring case: the user is in the dragging
1179 * state and he is moving his finger. We want to intercept this
1180 * motion.
1181 */
1182 final int action = ev.getAction();
1183 if ((action == MotionEvent.ACTION_MOVE) &&
1184 (mTouchState == TOUCH_STATE_SCROLLING)) {
1185 return true;
1186 }
1187
Winson Chung321e9ee2010-08-09 13:37:56 -07001188 switch (action & MotionEvent.ACTION_MASK) {
1189 case MotionEvent.ACTION_MOVE: {
1190 /*
1191 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1192 * whether the user has moved far enough from his original down touch.
1193 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001194 if (mActivePointerId != INVALID_POINTER) {
1195 determineScrollingStart(ev);
1196 break;
1197 }
1198 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1199 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1200 // i.e. fall through to the next case (don't break)
1201 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1202 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001203 }
1204
1205 case MotionEvent.ACTION_DOWN: {
1206 final float x = ev.getX();
1207 final float y = ev.getY();
1208 // Remember location of down touch
1209 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001210 mDownMotionY = y;
1211 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001212 mLastMotionX = x;
1213 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001214 float[] p = mapPointFromViewToParent(this, x, y);
1215 mParentDownMotionX = p[0];
1216 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001217 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001218 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001219 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001220
1221 // Determine if the down event is within the threshold to be an edge swipe
1222 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1223 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1224 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1225 mDownEventOnEdge = true;
1226 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001227
1228 /*
1229 * If being flinged and user touches the screen, initiate drag;
1230 * otherwise don't. mScroller.isFinished should be false when
1231 * being flinged.
1232 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001233 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001234 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1235 if (finishedScrolling) {
1236 mTouchState = TOUCH_STATE_REST;
1237 mScroller.abortAnimation();
1238 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001239 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1240 mTouchState = TOUCH_STATE_SCROLLING;
1241 } else {
1242 mTouchState = TOUCH_STATE_REST;
1243 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001244 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001245
Winson Chung86f77532010-08-24 11:08:22 -07001246 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001247 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001248 if (!DISABLE_TOUCH_SIDE_PAGES) {
1249 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1250 if (getChildCount() > 0) {
1251 if (hitsPreviousPage(x, y)) {
1252 mTouchState = TOUCH_STATE_PREV_PAGE;
1253 } else if (hitsNextPage(x, y)) {
1254 mTouchState = TOUCH_STATE_NEXT_PAGE;
1255 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001256 }
1257 }
1258 }
1259 break;
1260 }
1261
Winson Chung321e9ee2010-08-09 13:37:56 -07001262 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001263 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001264 resetTouchState();
1265 // Just intercept the touch event on up if we tap outside the strict viewport
1266 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1267 return true;
1268 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001269 break;
1270
1271 case MotionEvent.ACTION_POINTER_UP:
1272 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001273 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001274 break;
1275 }
1276
1277 /*
1278 * The only time we want to intercept motion events is if we are in the
1279 * drag mode.
1280 */
1281 return mTouchState != TOUCH_STATE_REST;
1282 }
1283
Adam Cohenf8d28232011-02-01 21:47:00 -08001284 protected void determineScrollingStart(MotionEvent ev) {
1285 determineScrollingStart(ev, 1.0f);
1286 }
1287
Winson Chung321e9ee2010-08-09 13:37:56 -07001288 /*
1289 * Determines if we should change the touch state to start scrolling after the
1290 * user moves their touch point too far.
1291 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001292 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001293 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001294 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001295 if (pointerIndex == -1) return;
1296
1297 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001298 final float x = ev.getX(pointerIndex);
1299 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001300 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1301
1302 // If we're only allowing edge swipes, we break out early if the down event wasn't
1303 // at the edge.
1304 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1305
Winson Chung321e9ee2010-08-09 13:37:56 -07001306 final int xDiff = (int) Math.abs(x - mLastMotionX);
1307 final int yDiff = (int) Math.abs(y - mLastMotionY);
1308
Adam Cohenf8d28232011-02-01 21:47:00 -08001309 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001310 boolean xPaged = xDiff > mPagingTouchSlop;
1311 boolean xMoved = xDiff > touchSlop;
1312 boolean yMoved = yDiff > touchSlop;
1313
Adam Cohenf8d28232011-02-01 21:47:00 -08001314 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001315 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001316 // Scroll if the user moved far enough along the X axis
1317 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001318 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001319 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001320 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001321 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001322 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1323 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001324 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001325 }
1326 }
1327
Adam Cohen7d30a372013-07-01 17:03:59 -07001328 protected float getMaxScrollProgress() {
1329 return 1.0f;
1330 }
1331
Adam Cohenf8d28232011-02-01 21:47:00 -08001332 protected void cancelCurrentPageLongPress() {
1333 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001334 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001335 // Try canceling the long press. It could also have been scheduled
1336 // by a distant descendant, so use the mAllowLongPress flag to block
1337 // everything
1338 final View currentPage = getPageAt(mCurrentPage);
1339 if (currentPage != null) {
1340 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001341 }
1342 }
1343 }
1344
Adam Cohen7d30a372013-07-01 17:03:59 -07001345 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1346 final int halfScreenSize = getViewportWidth() / 2;
1347
1348 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1349 screenCenter = Math.max(halfScreenSize, screenCenter);
1350
1351 return getScrollProgress(screenCenter, v, page);
1352 }
1353
Adam Cohenb5ba0972011-09-07 18:02:31 -07001354 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001355 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001356
1357 int totalDistance = getScaledMeasuredWidth(v) + mPageSpacing;
1358 int delta = screenCenter - (getChildOffset(page) -
1359 getRelativeChildOffset(page) + halfScreenSize);
1360
1361 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001362 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1363 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001364 return scrollProgress;
1365 }
1366
Adam Cohene0f66b52010-11-23 15:06:07 -08001367 // This curve determines how the effect of scrolling over the limits of the page dimishes
1368 // as the user pulls further and further from the bounds
1369 private float overScrollInfluenceCurve(float f) {
1370 f -= 1.0f;
1371 return f * f * f + 1.0f;
1372 }
1373
Adam Cohenb5ba0972011-09-07 18:02:31 -07001374 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001375 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001376
1377 // We want to reach the max over scroll effect when the user has
1378 // over scrolled half the size of the screen
1379 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1380
1381 if (f == 0) return;
1382
1383 // Clamp this factor, f, to -1 < f < 1
1384 if (Math.abs(f) >= 1) {
1385 f /= Math.abs(f);
1386 }
1387
1388 int overScrollAmount = (int) Math.round(f * screenSize);
1389 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001390 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001391 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001392 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001393 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001394 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001395 }
1396 invalidate();
1397 }
1398
1399 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001400 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001401
1402 float f = (amount / screenSize);
1403
1404 if (f == 0) return;
1405 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1406
Adam Cohen7bfc9792011-01-28 13:52:37 -08001407 // Clamp this factor, f, to -1 < f < 1
1408 if (Math.abs(f) >= 1) {
1409 f /= Math.abs(f);
1410 }
1411
Adam Cohene0f66b52010-11-23 15:06:07 -08001412 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001413 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001414 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001415 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001416 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001417 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001418 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001419 }
1420 invalidate();
1421 }
1422
Adam Cohenb5ba0972011-09-07 18:02:31 -07001423 protected void overScroll(float amount) {
1424 dampedOverScroll(amount);
1425 }
1426
Michael Jurkac5b262c2011-01-12 20:24:50 -08001427 protected float maxOverScroll() {
1428 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001429 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001430 float f = 1.0f;
1431 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1432 return OVERSCROLL_DAMP_FACTOR * f;
1433 }
1434
Winson Chung321e9ee2010-08-09 13:37:56 -07001435 @Override
1436 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001437 if (DISABLE_TOUCH_INTERACTION) {
1438 return false;
1439 }
1440
Winson Chung45e1d6e2010-11-09 17:19:49 -08001441 // Skip touch handling if there are no pages to swipe
1442 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1443
Michael Jurkab8f06722010-10-10 15:58:46 -07001444 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001445
1446 final int action = ev.getAction();
1447
1448 switch (action & MotionEvent.ACTION_MASK) {
1449 case MotionEvent.ACTION_DOWN:
1450 /*
1451 * If being flinged and user touches, stop the fling. isFinished
1452 * will be false if being flinged.
1453 */
1454 if (!mScroller.isFinished()) {
1455 mScroller.abortAnimation();
1456 }
1457
1458 // Remember where the motion event started
1459 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001460 mDownMotionY = mLastMotionY = ev.getY();
1461 mDownScrollX = getScrollX();
1462 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1463 mParentDownMotionX = p[0];
1464 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001465 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001466 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001467 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001468
1469 // Determine if the down event is within the threshold to be an edge swipe
1470 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1471 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1472 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1473 mDownEventOnEdge = true;
1474 }
1475
Michael Jurka0142d492010-08-25 17:46:15 -07001476 if (mTouchState == TOUCH_STATE_SCROLLING) {
1477 pageBeginMoving();
1478 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001479 break;
1480
1481 case MotionEvent.ACTION_MOVE:
1482 if (mTouchState == TOUCH_STATE_SCROLLING) {
1483 // Scroll to follow the motion event
1484 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001485
1486 if (pointerIndex == -1) return true;
1487
Winson Chung321e9ee2010-08-09 13:37:56 -07001488 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001489 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001490
Adam Cohenaefd4e12011-02-14 16:39:38 -08001491 mTotalMotionX += Math.abs(deltaX);
1492
Winson Chungc0844aa2011-02-02 15:25:58 -08001493 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1494 // keep the remainder because we are actually testing if we've moved from the last
1495 // scrolled position (which is discrete).
1496 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001497 mTouchX += deltaX;
1498 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1499 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001500 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001501 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001502 } else {
1503 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001504 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001505 mLastMotionX = x;
1506 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001507 } else {
1508 awakenScrollBars();
1509 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001510 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1511 // Update the last motion position
1512 mLastMotionX = ev.getX();
1513 mLastMotionY = ev.getY();
1514
1515 // Update the parent down so that our zoom animations take this new movement into
1516 // account
1517 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1518 mParentDownMotionX = pt[0];
1519 mParentDownMotionY = pt[1];
1520 updateDragViewTranslationDuringDrag();
1521
1522 // Find the closest page to the touch point
1523 final int dragViewIndex = indexOfChild(mDragView);
1524 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1525 getViewportWidth());
1526 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1527 + bufferSize);
1528 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1529 - bufferSize);
1530
1531 // Change the drag view if we are hovering over the drop target
1532 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1533 (int) mParentDownMotionX, (int) mParentDownMotionY);
1534 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1535
1536 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1537 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1538 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1539 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1540 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1541 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1542
1543 float parentX = mParentDownMotionX;
1544 int pageIndexToSnapTo = -1;
1545 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1546 pageIndexToSnapTo = dragViewIndex - 1;
1547 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1548 pageIndexToSnapTo = dragViewIndex + 1;
1549 }
1550
1551 final int pageUnderPointIndex = pageIndexToSnapTo;
1552 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1553 mTempVisiblePagesRange[0] = 0;
1554 mTempVisiblePagesRange[1] = getPageCount() - 1;
1555 boundByReorderablePages(true, mTempVisiblePagesRange);
1556 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1557 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1558 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1559 mSidePageHoverIndex = pageUnderPointIndex;
1560 mSidePageHoverRunnable = new Runnable() {
1561 @Override
1562 public void run() {
1563 // Update the down scroll position to account for the fact that the
1564 // current page is moved
1565 mDownScrollX = getChildOffset(pageUnderPointIndex)
1566 - getRelativeChildOffset(pageUnderPointIndex);
1567
1568 // Setup the scroll to the correct page before we swap the views
1569 snapToPage(pageUnderPointIndex);
1570
1571 // For each of the pages between the paged view and the drag view,
1572 // animate them from the previous position to the new position in
1573 // the layout (as a result of the drag view moving in the layout)
1574 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1575 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1576 dragViewIndex + 1 : pageUnderPointIndex;
1577 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1578 dragViewIndex - 1 : pageUnderPointIndex;
1579 for (int i = lowerIndex; i <= upperIndex; ++i) {
1580 View v = getChildAt(i);
1581 // dragViewIndex < pageUnderPointIndex, so after we remove the
1582 // drag view all subsequent views to pageUnderPointIndex will
1583 // shift down.
1584 int oldX = getViewportOffsetX() + getChildOffset(i);
1585 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1586
1587 // Animate the view translation from its old position to its new
1588 // position
1589 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1590 if (anim != null) {
1591 anim.cancel();
1592 }
1593
1594 v.setTranslationX(oldX - newX);
1595 anim = new AnimatorSet();
1596 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1597 anim.playTogether(
1598 ObjectAnimator.ofFloat(v, "translationX", 0f));
1599 anim.start();
1600 v.setTag(anim);
1601 }
1602
1603 removeView(mDragView);
1604 onRemoveView(mDragView, false);
1605 addView(mDragView, pageUnderPointIndex);
1606 onAddView(mDragView, pageUnderPointIndex);
1607 mSidePageHoverIndex = -1;
1608 }
1609 };
1610 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1611 }
1612 } else {
1613 removeCallbacks(mSidePageHoverRunnable);
1614 mSidePageHoverIndex = -1;
1615 }
Adam Cohen564976a2010-10-13 18:52:07 -07001616 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001617 determineScrollingStart(ev);
1618 }
1619 break;
1620
1621 case MotionEvent.ACTION_UP:
1622 if (mTouchState == TOUCH_STATE_SCROLLING) {
1623 final int activePointerId = mActivePointerId;
1624 final int pointerIndex = ev.findPointerIndex(activePointerId);
1625 final float x = ev.getX(pointerIndex);
1626 final VelocityTracker velocityTracker = mVelocityTracker;
1627 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1628 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001629 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen00481b32011-11-18 12:03:48 -08001630 final int pageWidth = getScaledMeasuredWidth(getPageAt(mCurrentPage));
1631 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1632 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001633
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001634 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1635
Adam Cohen00481b32011-11-18 12:03:48 -08001636 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001637 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001638
Adam Cohenaefd4e12011-02-14 16:39:38 -08001639 // In the case that the page is moved far to one direction and then is flung
1640 // in the opposite direction, we use a threshold to determine whether we should
1641 // just return to the starting page, or if we should skip one further.
1642 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001643 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001644 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001645 returnToOriginalPage = true;
1646 }
1647
Adam Cohenaefd4e12011-02-14 16:39:38 -08001648 int finalPage;
1649 // We give flings precedence over large moves, which is why we short-circuit our
1650 // test for a large move if a fling has been registered. That is, a large
1651 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001652 final boolean isRtl = isLayoutRtl();
1653 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1654 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1655 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1656 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001657 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1658 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001659 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1660 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001661 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001662 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1663 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001664 } else {
1665 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001666 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001667 // at this point we have not moved beyond the touch slop
1668 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1669 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001670 int nextPage = Math.max(0, mCurrentPage - 1);
1671 if (nextPage != mCurrentPage) {
1672 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001673 } else {
1674 snapToDestination();
1675 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001676 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001677 // at this point we have not moved beyond the touch slop
1678 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1679 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001680 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1681 if (nextPage != mCurrentPage) {
1682 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001683 } else {
1684 snapToDestination();
1685 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001686 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1687 // Update the last motion position
1688 mLastMotionX = ev.getX();
1689 mLastMotionY = ev.getY();
1690
1691 // Update the parent down so that our zoom animations take this new movement into
1692 // account
1693 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1694 mParentDownMotionX = pt[0];
1695 mParentDownMotionY = pt[1];
1696 updateDragViewTranslationDuringDrag();
1697 boolean handledFling = false;
1698 if (!DISABLE_FLING_TO_DELETE) {
1699 // Check the velocity and see if we are flinging-to-delete
1700 PointF flingToDeleteVector = isFlingingToDelete();
1701 if (flingToDeleteVector != null) {
1702 onFlingToDelete(flingToDeleteVector);
1703 handledFling = true;
1704 }
1705 }
1706 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1707 (int) mParentDownMotionY)) {
1708 onDropToDelete();
1709 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001710 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001711 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001712 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001713
1714 // Remove the callback to wait for the side page hover timeout
1715 removeCallbacks(mSidePageHoverRunnable);
1716 // End any intermediate reordering states
1717 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001718 break;
1719
1720 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001721 if (mTouchState == TOUCH_STATE_SCROLLING) {
1722 snapToDestination();
1723 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001724 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001725 break;
1726
1727 case MotionEvent.ACTION_POINTER_UP:
1728 onSecondaryPointerUp(ev);
1729 break;
1730 }
1731
1732 return true;
1733 }
1734
Adam Cohen7d30a372013-07-01 17:03:59 -07001735 public void onFlingToDelete(View v) {}
1736 public void onRemoveView(View v, boolean deletePermanently) {}
1737 public void onRemoveViewAnimationCompleted() {}
1738 public void onAddView(View v, int index) {}
1739
1740 private void resetTouchState() {
1741 releaseVelocityTracker();
1742 endReordering();
1743 mTouchState = TOUCH_STATE_REST;
1744 mActivePointerId = INVALID_POINTER;
1745 mDownEventOnEdge = false;
1746 }
1747
1748 protected void onUnhandledTap(MotionEvent ev) {}
1749
Winson Chung185d7162011-02-28 13:47:29 -08001750 @Override
1751 public boolean onGenericMotionEvent(MotionEvent event) {
1752 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1753 switch (event.getAction()) {
1754 case MotionEvent.ACTION_SCROLL: {
1755 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1756 final float vscroll;
1757 final float hscroll;
1758 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1759 vscroll = 0;
1760 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1761 } else {
1762 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1763 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1764 }
1765 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001766 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1767 : (hscroll > 0 || vscroll > 0);
1768 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001769 scrollRight();
1770 } else {
1771 scrollLeft();
1772 }
1773 return true;
1774 }
1775 }
1776 }
1777 }
1778 return super.onGenericMotionEvent(event);
1779 }
1780
Michael Jurkab8f06722010-10-10 15:58:46 -07001781 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1782 if (mVelocityTracker == null) {
1783 mVelocityTracker = VelocityTracker.obtain();
1784 }
1785 mVelocityTracker.addMovement(ev);
1786 }
1787
1788 private void releaseVelocityTracker() {
1789 if (mVelocityTracker != null) {
1790 mVelocityTracker.recycle();
1791 mVelocityTracker = null;
1792 }
1793 }
1794
Winson Chung321e9ee2010-08-09 13:37:56 -07001795 private void onSecondaryPointerUp(MotionEvent ev) {
1796 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1797 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1798 final int pointerId = ev.getPointerId(pointerIndex);
1799 if (pointerId == mActivePointerId) {
1800 // This was our active pointer going up. Choose a new
1801 // active pointer and adjust accordingly.
1802 // TODO: Make this decision more intelligent.
1803 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1804 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1805 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001806 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001807 mActivePointerId = ev.getPointerId(newPointerIndex);
1808 if (mVelocityTracker != null) {
1809 mVelocityTracker.clear();
1810 }
1811 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001812 }
1813
Winson Chung321e9ee2010-08-09 13:37:56 -07001814 @Override
1815 public void requestChildFocus(View child, View focused) {
1816 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001817 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001818 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001819 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001820 }
1821 }
1822
Winson Chunge3193b92010-09-10 11:44:42 -07001823 protected int getChildIndexForRelativeOffset(int relativeOffset) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001824 final boolean isRtl = isLayoutRtl();
Winson Chunge3193b92010-09-10 11:44:42 -07001825 final int childCount = getChildCount();
Adam Cohen9c4949e2010-10-05 12:27:22 -07001826 int left;
1827 int right;
Adam Cohen0ffac432013-07-10 11:19:26 -07001828 final int startIndex = isRtl ? childCount - 1 : 0;
1829 final int endIndex = isRtl ? -1 : childCount;
1830 final int delta = isRtl ? -1 : 1;
1831 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen9c4949e2010-10-05 12:27:22 -07001832 left = getRelativeChildOffset(i);
Adam Cohen22f823d2011-09-01 17:22:18 -07001833 right = (left + getScaledMeasuredWidth(getPageAt(i)));
Winson Chunge3193b92010-09-10 11:44:42 -07001834 if (left <= relativeOffset && relativeOffset <= right) {
1835 return i;
1836 }
Winson Chunge3193b92010-09-10 11:44:42 -07001837 }
1838 return -1;
1839 }
1840
Winson Chung1908d072011-02-24 18:09:44 -08001841 protected int getChildWidth(int index) {
Winson Chung63257c12011-05-05 17:06:13 -07001842 // This functions are called enough times that it actually makes a difference in the
1843 // profiler -- so just inline the max() here
Adam Cohen22f823d2011-09-01 17:22:18 -07001844 final int measuredWidth = getPageAt(index).getMeasuredWidth();
Winson Chung63257c12011-05-05 17:06:13 -07001845 final int minWidth = mMinimumWidth;
1846 return (minWidth > measuredWidth) ? minWidth : measuredWidth;
Winson Chung1908d072011-02-24 18:09:44 -08001847 }
1848
Adam Cohen7d30a372013-07-01 17:03:59 -07001849 int getPageNearestToPoint(float x) {
1850 int index = 0;
1851 for (int i = 0; i < getChildCount(); ++i) {
1852 if (x < getChildAt(i).getRight() - getScrollX()) {
1853 return index;
1854 } else {
1855 index++;
1856 }
1857 }
1858 return Math.min(index, getChildCount() - 1);
1859 }
1860
Adam Cohend19d3ca2010-09-15 14:43:42 -07001861 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001862 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001863 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001864 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001865 final int childCount = getChildCount();
1866 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001867 View layout = (View) getPageAt(i);
Michael Jurkad3ef3062010-11-23 16:23:58 -08001868 int childWidth = getScaledMeasuredWidth(layout);
Winson Chung321e9ee2010-08-09 13:37:56 -07001869 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001870 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001871 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1872 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1873 minDistanceFromScreenCenter = distanceFromScreenCenter;
1874 minDistanceFromScreenCenterIndex = i;
1875 }
1876 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001877 return minDistanceFromScreenCenterIndex;
1878 }
1879
1880 protected void snapToDestination() {
1881 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001882 }
1883
Adam Cohene0f66b52010-11-23 15:06:07 -08001884 private static class ScrollInterpolator implements Interpolator {
1885 public ScrollInterpolator() {
1886 }
1887
1888 public float getInterpolation(float t) {
1889 t -= 1.0f;
1890 return t*t*t*t*t + 1;
1891 }
1892 }
1893
1894 // We want the duration of the page snap animation to be influenced by the distance that
1895 // the screen has to travel, however, we don't want this duration to be effected in a
1896 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1897 // of travel has on the overall snap duration.
1898 float distanceInfluenceForSnapDuration(float f) {
1899 f -= 0.5f; // center the values about 0.
1900 f *= 0.3f * Math.PI / 2.0f;
1901 return (float) Math.sin(f);
1902 }
1903
Michael Jurka0142d492010-08-25 17:46:15 -07001904 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001905 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001906 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001907
Winson Chung785d2eb2011-04-14 16:08:02 -07001908 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
1909 if (DEBUG) Log.d(TAG, "snapToPageWithVelocity.getRelativeChildOffset(): "
Adam Cohen7d30a372013-07-01 17:03:59 -07001910 + getViewportWidth() + ", " + getChildWidth(whichPage));
Adam Cohene0f66b52010-11-23 15:06:07 -08001911 final int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
1912 int delta = newX - mUnboundedScrollX;
1913 int duration = 0;
1914
Adam Cohen265b9a62011-12-07 14:37:18 -08001915 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001916 // If the velocity is low enough, then treat this more as an automatic page advance
1917 // as opposed to an apparent physical response to flinging
1918 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1919 return;
1920 }
1921
1922 // Here we compute a "distance" that will be used in the computation of the overall
1923 // snap duration. This is a function of the actual distance that needs to be traveled;
1924 // we keep this value close to half screen size in order to reduce the variance in snap
1925 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001926 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001927 float distance = halfScreenSize + halfScreenSize *
1928 distanceInfluenceForSnapDuration(distanceRatio);
1929
1930 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001931 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001932
1933 // we want the page's snap velocity to approximately match the velocity at which the
1934 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001935 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1936 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001937
1938 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001939 }
1940
1941 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001942 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001943 }
1944
Adam Cohen7d30a372013-07-01 17:03:59 -07001945 protected void snapToPageImmediately(int whichPage) {
1946 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1947 }
1948
Michael Jurka0142d492010-08-25 17:46:15 -07001949 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001950 snapToPage(whichPage, duration, false);
1951 }
1952
1953 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001954 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001955
Winson Chung785d2eb2011-04-14 16:08:02 -07001956 if (DEBUG) Log.d(TAG, "snapToPage.getChildOffset(): " + getChildOffset(whichPage));
Adam Cohen7d30a372013-07-01 17:03:59 -07001957 if (DEBUG) Log.d(TAG, "snapToPage.getRelativeChildOffset(): " + getViewportWidth() + ", "
Winson Chung785d2eb2011-04-14 16:08:02 -07001958 + getChildWidth(whichPage));
Winson Chung86f77532010-08-24 11:08:22 -07001959 int newX = getChildOffset(whichPage) - getRelativeChildOffset(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08001960 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001961 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07001962 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07001963 }
1964
1965 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001966 snapToPage(whichPage, delta, duration, false);
1967 }
Michael Jurka0142d492010-08-25 17:46:15 -07001968
Adam Cohen7d30a372013-07-01 17:03:59 -07001969 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
1970 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07001971 View focusedChild = getFocusedChild();
1972 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07001973 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07001974 focusedChild.clearFocus();
1975 }
1976
1977 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001978 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07001979 if (immediate) {
1980 duration = 0;
1981 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001982 duration = Math.abs(delta);
1983 }
1984
1985 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08001986 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07001987
Michael Jurka0142d492010-08-25 17:46:15 -07001988 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07001989
1990 // Trigger a compute() to finish switching pages if necessary
1991 if (immediate) {
1992 computeScroll();
1993 }
1994
1995 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07001996 invalidate();
1997 }
1998
Winson Chung321e9ee2010-08-09 13:37:56 -07001999 public void scrollLeft() {
2000 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002001 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002002 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002003 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002004 }
2005 }
2006
2007 public void scrollRight() {
2008 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002009 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002010 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002011 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002012 }
2013 }
2014
Winson Chung86f77532010-08-24 11:08:22 -07002015 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002016 int result = -1;
2017 if (v != null) {
2018 ViewParent vp = v.getParent();
2019 int count = getChildCount();
2020 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002021 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002022 return i;
2023 }
2024 }
2025 }
2026 return result;
2027 }
2028
2029 /**
2030 * @return True is long presses are still allowed for the current touch
2031 */
2032 public boolean allowLongPress() {
2033 return mAllowLongPress;
2034 }
2035
Michael Jurka0142d492010-08-25 17:46:15 -07002036 /**
2037 * Set true to allow long-press events to be triggered, usually checked by
2038 * {@link Launcher} to accept or block dpad-initiated long-presses.
2039 */
2040 public void setAllowLongPress(boolean allowLongPress) {
2041 mAllowLongPress = allowLongPress;
2042 }
2043
Winson Chung321e9ee2010-08-09 13:37:56 -07002044 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002045 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002046
2047 SavedState(Parcelable superState) {
2048 super(superState);
2049 }
2050
2051 private SavedState(Parcel in) {
2052 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002053 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002054 }
2055
2056 @Override
2057 public void writeToParcel(Parcel out, int flags) {
2058 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002059 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002060 }
2061
2062 public static final Parcelable.Creator<SavedState> CREATOR =
2063 new Parcelable.Creator<SavedState>() {
2064 public SavedState createFromParcel(Parcel in) {
2065 return new SavedState(in);
2066 }
2067
2068 public SavedState[] newArray(int size) {
2069 return new SavedState[size];
2070 }
2071 };
2072 }
2073
Winson Chungf314b0e2011-08-16 11:54:27 -07002074 protected void loadAssociatedPages(int page) {
2075 loadAssociatedPages(page, false);
2076 }
2077 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002078 if (mContentIsRefreshable) {
2079 final int count = getChildCount();
2080 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002081 int lowerPageBound = getAssociatedLowerPageBound(page);
2082 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002083 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2084 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002085 // First, clear any pages that should no longer be loaded
2086 for (int i = 0; i < count; ++i) {
2087 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002088 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002089 if (layout.getPageChildCount() > 0) {
2090 layout.removeAllViewsOnPage();
2091 }
2092 mDirtyPageContent.set(i, true);
2093 }
2094 }
2095 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002096 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002097 if ((i != page) && immediateAndOnly) {
2098 continue;
2099 }
Michael Jurka0142d492010-08-25 17:46:15 -07002100 if (lowerPageBound <= i && i <= upperPageBound) {
2101 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002102 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002103 mDirtyPageContent.set(i, false);
2104 }
Winson Chung86f77532010-08-24 11:08:22 -07002105 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002106 }
2107 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002108 }
2109 }
2110
Winson Chunge3193b92010-09-10 11:44:42 -07002111 protected int getAssociatedLowerPageBound(int page) {
2112 return Math.max(0, page - 1);
2113 }
2114 protected int getAssociatedUpperPageBound(int page) {
2115 final int count = getChildCount();
2116 return Math.min(page + 1, count - 1);
2117 }
2118
Winson Chung86f77532010-08-24 11:08:22 -07002119 /**
2120 * This method is called ONLY to synchronize the number of pages that the paged view has.
2121 * To actually fill the pages with information, implement syncPageItems() below. It is
2122 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2123 * and therefore, individual page items do not need to be updated in this method.
2124 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002125 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002126
2127 /**
2128 * This method is called to synchronize the items that are on a particular page. If views on
2129 * the page can be reused, then they should be updated within this method.
2130 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002131 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002132
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002133 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002134 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002135 }
2136 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002137 invalidatePageData(currentPage, false);
2138 }
2139 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002140 if (!mIsDataReady) {
2141 return;
2142 }
2143
Michael Jurka0142d492010-08-25 17:46:15 -07002144 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002145 // Force all scrolling-related behavior to end
2146 mScroller.forceFinished(true);
2147 mNextPage = INVALID_PAGE;
2148
Michael Jurka0142d492010-08-25 17:46:15 -07002149 // Update all the pages
2150 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002151
Winson Chung5a808352011-06-27 19:08:49 -07002152 // We must force a measure after we've loaded the pages to update the content width and
2153 // to determine the full scroll width
2154 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2155 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2156
2157 // Set a new page as the current page if necessary
2158 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002159 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002160 }
2161
Michael Jurka0142d492010-08-25 17:46:15 -07002162 // Mark each of the pages as dirty
2163 final int count = getChildCount();
2164 mDirtyPageContent.clear();
2165 for (int i = 0; i < count; ++i) {
2166 mDirtyPageContent.add(true);
2167 }
2168
2169 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002170 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002171 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002172 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002173 }
Winson Chung007c6982011-06-14 13:27:53 -07002174
Michael Jurkaafaa0502011-12-13 18:22:50 -08002175 protected View getScrollingIndicator() {
Winson Chung007c6982011-06-14 13:27:53 -07002176 // We use mHasScrollIndicator to prevent future lookups if there is no sibling indicator
2177 // found
2178 if (mHasScrollIndicator && mScrollIndicator == null) {
2179 ViewGroup parent = (ViewGroup) getParent();
Winson Chunga128a7b2012-04-30 15:23:15 -07002180 if (parent != null) {
2181 mScrollIndicator = (View) (parent.findViewById(R.id.paged_view_indicator));
2182 mHasScrollIndicator = mScrollIndicator != null;
2183 if (mHasScrollIndicator) {
2184 mScrollIndicator.setVisibility(View.VISIBLE);
2185 }
Winson Chung007c6982011-06-14 13:27:53 -07002186 }
2187 }
2188 return mScrollIndicator;
2189 }
2190
2191 protected boolean isScrollingIndicatorEnabled() {
Michael Jurkab1dfe252012-09-26 10:53:55 -07002192 return true;
Winson Chung007c6982011-06-14 13:27:53 -07002193 }
2194
Winson Chung5a808352011-06-27 19:08:49 -07002195 Runnable hideScrollingIndicatorRunnable = new Runnable() {
2196 @Override
2197 public void run() {
2198 hideScrollingIndicator(false);
2199 }
2200 };
Adam Cohen7d30a372013-07-01 17:03:59 -07002201
Michael Jurkab737ee62011-11-15 15:57:22 -08002202 protected void flashScrollingIndicator(boolean animated) {
Winson Chung5a808352011-06-27 19:08:49 -07002203 removeCallbacks(hideScrollingIndicatorRunnable);
Michael Jurkab737ee62011-11-15 15:57:22 -08002204 showScrollingIndicator(!animated);
Winson Chung5a808352011-06-27 19:08:49 -07002205 postDelayed(hideScrollingIndicatorRunnable, sScrollIndicatorFlashDuration);
Winson Chung3ac74c52011-06-30 17:39:37 -07002206 }
2207
Michael Jurka430e8a52011-08-08 15:52:14 -07002208 protected void showScrollingIndicator(boolean immediately) {
Michael Jurkabed61d22012-02-14 22:51:29 -08002209 mShouldShowScrollIndicator = true;
2210 mShouldShowScrollIndicatorImmediately = true;
Winson Chung007c6982011-06-14 13:27:53 -07002211 if (getChildCount() <= 1) return;
2212 if (!isScrollingIndicatorEnabled()) return;
2213
Michael Jurkabed61d22012-02-14 22:51:29 -08002214 mShouldShowScrollIndicator = false;
Winson Chung007c6982011-06-14 13:27:53 -07002215 getScrollingIndicator();
2216 if (mScrollIndicator != null) {
Winson Chung007c6982011-06-14 13:27:53 -07002217 // Fade the indicator in
2218 updateScrollingIndicatorPosition();
Winson Chung32174c82011-07-19 15:47:55 -07002219 mScrollIndicator.setVisibility(View.VISIBLE);
Adam Cohen21b41102011-11-01 17:29:52 -07002220 cancelScrollingIndicatorAnimations();
Adam Cohen7d30a372013-07-01 17:03:59 -07002221 if (immediately) {
Michael Jurka430e8a52011-08-08 15:52:14 -07002222 mScrollIndicator.setAlpha(1f);
2223 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07002224 mScrollIndicatorAnimator = ObjectAnimator.ofFloat(mScrollIndicator, "alpha", 1f);
Michael Jurka430e8a52011-08-08 15:52:14 -07002225 mScrollIndicatorAnimator.setDuration(sScrollIndicatorFadeInDuration);
2226 mScrollIndicatorAnimator.start();
2227 }
Winson Chung007c6982011-06-14 13:27:53 -07002228 }
2229 }
2230
Adam Cohen21b41102011-11-01 17:29:52 -07002231 protected void cancelScrollingIndicatorAnimations() {
2232 if (mScrollIndicatorAnimator != null) {
2233 mScrollIndicatorAnimator.cancel();
2234 }
2235 }
2236
Winson Chung007c6982011-06-14 13:27:53 -07002237 protected void hideScrollingIndicator(boolean immediately) {
Winson Chung007c6982011-06-14 13:27:53 -07002238 if (getChildCount() <= 1) return;
2239 if (!isScrollingIndicatorEnabled()) return;
2240
2241 getScrollingIndicator();
2242 if (mScrollIndicator != null) {
2243 // Fade the indicator out
2244 updateScrollingIndicatorPosition();
Adam Cohen21b41102011-11-01 17:29:52 -07002245 cancelScrollingIndicatorAnimations();
Adam Cohen7d30a372013-07-01 17:03:59 -07002246 if (immediately) {
Michael Jurka81efbad2011-11-03 13:50:45 -07002247 mScrollIndicator.setVisibility(View.INVISIBLE);
Winson Chung32174c82011-07-19 15:47:55 -07002248 mScrollIndicator.setAlpha(0f);
2249 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07002250 mScrollIndicatorAnimator = ObjectAnimator.ofFloat(mScrollIndicator, "alpha", 0f);
Winson Chung32174c82011-07-19 15:47:55 -07002251 mScrollIndicatorAnimator.setDuration(sScrollIndicatorFadeOutDuration);
2252 mScrollIndicatorAnimator.addListener(new AnimatorListenerAdapter() {
2253 private boolean cancelled = false;
2254 @Override
2255 public void onAnimationCancel(android.animation.Animator animation) {
2256 cancelled = true;
2257 }
2258 @Override
2259 public void onAnimationEnd(Animator animation) {
2260 if (!cancelled) {
Michael Jurka81efbad2011-11-03 13:50:45 -07002261 mScrollIndicator.setVisibility(View.INVISIBLE);
Winson Chung32174c82011-07-19 15:47:55 -07002262 }
2263 }
2264 });
2265 mScrollIndicatorAnimator.start();
2266 }
Winson Chung007c6982011-06-14 13:27:53 -07002267 }
2268 }
2269
Winson Chung32174c82011-07-19 15:47:55 -07002270 /**
2271 * To be overridden by subclasses to determine whether the scroll indicator should stretch to
2272 * fill its space on the track or not.
2273 */
2274 protected boolean hasElasticScrollIndicator() {
Winson Chungdea74b72011-09-13 18:06:43 -07002275 return true;
Winson Chung32174c82011-07-19 15:47:55 -07002276 }
2277
Winson Chung007c6982011-06-14 13:27:53 -07002278 private void updateScrollingIndicator() {
Winson Chung007c6982011-06-14 13:27:53 -07002279 if (getChildCount() <= 1) return;
2280 if (!isScrollingIndicatorEnabled()) return;
2281
2282 getScrollingIndicator();
2283 if (mScrollIndicator != null) {
2284 updateScrollingIndicatorPosition();
2285 }
Michael Jurkabed61d22012-02-14 22:51:29 -08002286 if (mShouldShowScrollIndicator) {
2287 showScrollingIndicator(mShouldShowScrollIndicatorImmediately);
2288 }
Winson Chung007c6982011-06-14 13:27:53 -07002289 }
2290
Winson Chung007c6982011-06-14 13:27:53 -07002291 private void updateScrollingIndicatorPosition() {
Adam Cohen0ffac432013-07-10 11:19:26 -07002292 final boolean isRtl = isLayoutRtl();
Winson Chung649723c2011-07-06 20:41:23 -07002293 if (!isScrollingIndicatorEnabled()) return;
Michael Jurka430e8a52011-08-08 15:52:14 -07002294 if (mScrollIndicator == null) return;
Winson Chung32174c82011-07-19 15:47:55 -07002295 int numPages = getChildCount();
Adam Cohen7d30a372013-07-01 17:03:59 -07002296 int pageWidth = getViewportWidth();
2297 int lastChildIndex = Math.max(0, getChildCount() - 1);
2298 int maxScrollX = getChildOffset(lastChildIndex) - getRelativeChildOffset(lastChildIndex);
Winson Chungf5f8cef2011-07-22 11:16:13 -07002299 int trackWidth = pageWidth - mScrollIndicatorPaddingLeft - mScrollIndicatorPaddingRight;
Winson Chung32174c82011-07-19 15:47:55 -07002300 int indicatorWidth = mScrollIndicator.getMeasuredWidth() -
2301 mScrollIndicator.getPaddingLeft() - mScrollIndicator.getPaddingRight();
Winson Chung32174c82011-07-19 15:47:55 -07002302
Adam Cohen0ffac432013-07-10 11:19:26 -07002303 float scrollPos = isRtl ? mMaxScrollX - getScrollX() : getScrollX();
2304 float offset = Math.max(0f, Math.min(1f, (float) scrollPos / mMaxScrollX));
2305 if (isRtl) {
2306 offset = 1f - offset;
2307 }
Winson Chung32174c82011-07-19 15:47:55 -07002308 int indicatorSpace = trackWidth / numPages;
Winson Chungae890b82011-09-13 18:08:54 -07002309 int indicatorPos = (int) (offset * (trackWidth - indicatorSpace)) + mScrollIndicatorPaddingLeft;
Winson Chung32174c82011-07-19 15:47:55 -07002310 if (hasElasticScrollIndicator()) {
2311 if (mScrollIndicator.getMeasuredWidth() != indicatorSpace) {
2312 mScrollIndicator.getLayoutParams().width = indicatorSpace;
2313 mScrollIndicator.requestLayout();
2314 }
2315 } else {
2316 int indicatorCenterOffset = indicatorSpace / 2 - indicatorWidth / 2;
2317 indicatorPos += indicatorCenterOffset;
2318 }
Winson Chung007c6982011-06-14 13:27:53 -07002319 mScrollIndicator.setTranslationX(indicatorPos);
Winson Chung3ac74c52011-06-30 17:39:37 -07002320 }
2321
Adam Cohen7d30a372013-07-01 17:03:59 -07002322 // Animate the drag view back to the original position
2323 void animateDragViewToOriginalPosition() {
2324 if (mDragView != null) {
2325 AnimatorSet anim = new AnimatorSet();
2326 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2327 anim.playTogether(
2328 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2329 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2330 anim.addListener(new AnimatorListenerAdapter() {
2331 @Override
2332 public void onAnimationEnd(Animator animation) {
2333 onPostReorderingAnimationCompleted();
2334 }
2335 });
2336 anim.start();
2337 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002338 }
2339
Adam Cohen7d30a372013-07-01 17:03:59 -07002340 // "Zooms out" the PagedView to reveal more side pages
2341 protected boolean zoomOut() {
2342 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2343 mZoomInOutAnim.cancel();
2344 }
2345
2346 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2347 mZoomInOutAnim = new AnimatorSet();
2348 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2349 mZoomInOutAnim.playTogether(
2350 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2351 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2352 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2353 @Override
2354 public void onAnimationStart(Animator animation) {
2355 // Show the delete drop target
2356 if (mDeleteDropTarget != null) {
2357 mDeleteDropTarget.setVisibility(View.VISIBLE);
2358 mDeleteDropTarget.animate().alpha(1f)
2359 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2360 .setListener(new AnimatorListenerAdapter() {
2361 @Override
2362 public void onAnimationStart(Animator animation) {
2363 mDeleteDropTarget.setAlpha(0f);
2364 }
2365 });
2366 }
2367 }
2368 });
2369 mZoomInOutAnim.start();
2370 return true;
2371 }
2372 return false;
2373 }
2374
2375 protected void onStartReordering() {
2376 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2377 mTouchState = TOUCH_STATE_REORDERING;
2378 mIsReordering = true;
2379
2380 // Mark all the non-widget pages as invisible
2381 getVisiblePages(mTempVisiblePagesRange);
2382 boundByReorderablePages(true, mTempVisiblePagesRange);
2383 for (int i = 0; i < getPageCount(); ++i) {
2384 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2385 getPageAt(i).setAlpha(0f);
2386 }
2387 }
2388
2389 // We must invalidate to trigger a redraw to update the layers such that the drag view
2390 // is always drawn on top
2391 invalidate();
2392 }
2393
2394 private void onPostReorderingAnimationCompleted() {
2395 // Trigger the callback when reordering has settled
2396 --mPostReorderingPreZoomInRemainingAnimationCount;
2397 if (mPostReorderingPreZoomInRunnable != null &&
2398 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2399 mPostReorderingPreZoomInRunnable.run();
2400 mPostReorderingPreZoomInRunnable = null;
2401 }
2402 }
2403
2404 protected void onEndReordering() {
2405 mIsReordering = false;
2406
2407 // Mark all the non-widget pages as visible again
2408 getVisiblePages(mTempVisiblePagesRange);
2409 boundByReorderablePages(true, mTempVisiblePagesRange);
2410 for (int i = 0; i < getPageCount(); ++i) {
2411 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2412 getPageAt(i).setAlpha(1f);
2413 }
2414 }
2415 }
2416
2417 public boolean startReordering() {
2418 int dragViewIndex = getPageNearestToCenterOfScreen();
2419 mTempVisiblePagesRange[0] = 0;
2420 mTempVisiblePagesRange[1] = getPageCount() - 1;
2421 boundByReorderablePages(true, mTempVisiblePagesRange);
2422 mReorderingStarted = true;
2423
2424 // Check if we are within the reordering range
2425 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2426 dragViewIndex <= mTempVisiblePagesRange[1]) {
2427 if (zoomOut()) {
2428 // Find the drag view under the pointer
2429 mDragView = getChildAt(dragViewIndex);
2430
2431 onStartReordering();
2432 }
2433 return true;
2434 }
2435 return false;
2436 }
2437
2438 boolean isReordering(boolean testTouchState) {
2439 boolean state = mIsReordering;
2440 if (testTouchState) {
2441 state &= (mTouchState == TOUCH_STATE_REORDERING);
2442 }
2443 return state;
2444 }
2445 void endReordering() {
2446 // For simplicity, we call endReordering sometimes even if reordering was never started.
2447 // In that case, we don't want to do anything.
2448 if (!mReorderingStarted) return;
2449 mReorderingStarted = false;
2450
2451 // If we haven't flung-to-delete the current child, then we just animate the drag view
2452 // back into position
2453 final Runnable onCompleteRunnable = new Runnable() {
2454 @Override
2455 public void run() {
2456 onEndReordering();
2457 }
2458 };
2459 if (!mDeferringForDelete) {
2460 mPostReorderingPreZoomInRunnable = new Runnable() {
2461 public void run() {
2462 zoomIn(onCompleteRunnable);
2463 };
2464 };
2465
2466 mPostReorderingPreZoomInRemainingAnimationCount =
2467 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2468 // Snap to the current page
2469 snapToPage(indexOfChild(mDragView), 0);
2470 // Animate the drag view back to the front position
2471 animateDragViewToOriginalPosition();
2472 } else {
2473 // Handled in post-delete-animation-callbacks
2474 }
2475 }
2476
2477 // "Zooms in" the PagedView to highlight the current page
2478 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2479 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2480 mZoomInOutAnim.cancel();
2481 }
2482 if (getScaleX() < 1f || getScaleY() < 1f) {
2483 mZoomInOutAnim = new AnimatorSet();
2484 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2485 mZoomInOutAnim.playTogether(
2486 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2487 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2488 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2489 @Override
2490 public void onAnimationStart(Animator animation) {
2491 // Hide the delete drop target
2492 if (mDeleteDropTarget != null) {
2493 mDeleteDropTarget.animate().alpha(0f)
2494 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2495 .setListener(new AnimatorListenerAdapter() {
2496 @Override
2497 public void onAnimationEnd(Animator animation) {
2498 mDeleteDropTarget.setVisibility(View.GONE);
2499 }
2500 });
2501 }
2502 }
2503 @Override
2504 public void onAnimationCancel(Animator animation) {
2505 mDragView = null;
2506 }
2507 @Override
2508 public void onAnimationEnd(Animator animation) {
2509 mDragView = null;
2510 if (onCompleteRunnable != null) {
2511 onCompleteRunnable.run();
2512 }
2513 }
2514 });
2515 mZoomInOutAnim.start();
2516 return true;
2517 } else {
2518 if (onCompleteRunnable != null) {
2519 onCompleteRunnable.run();
2520 }
2521 }
2522 return false;
2523 }
2524
2525 /*
2526 * Flinging to delete - IN PROGRESS
2527 */
2528 private PointF isFlingingToDelete() {
2529 ViewConfiguration config = ViewConfiguration.get(getContext());
2530 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2531
2532 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2533 // Do a quick dot product test to ensure that we are flinging upwards
2534 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2535 mVelocityTracker.getYVelocity());
2536 PointF upVec = new PointF(0f, -1f);
2537 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2538 (vel.length() * upVec.length()));
2539 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2540 return vel;
2541 }
2542 }
2543 return null;
2544 }
2545
2546 /**
2547 * Creates an animation from the current drag view along its current velocity vector.
2548 * For this animation, the alpha runs for a fixed duration and we update the position
2549 * progressively.
2550 */
2551 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2552 private View mDragView;
2553 private PointF mVelocity;
2554 private Rect mFrom;
2555 private long mPrevTime;
2556 private float mFriction;
2557
2558 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2559
2560 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2561 long startTime, float friction) {
2562 mDragView = dragView;
2563 mVelocity = vel;
2564 mFrom = from;
2565 mPrevTime = startTime;
2566 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2567 }
2568
2569 @Override
2570 public void onAnimationUpdate(ValueAnimator animation) {
2571 float t = ((Float) animation.getAnimatedValue()).floatValue();
2572 long curTime = AnimationUtils.currentAnimationTimeMillis();
2573
2574 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2575 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2576
2577 mDragView.setTranslationX(mFrom.left);
2578 mDragView.setTranslationY(mFrom.top);
2579 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2580
2581 mVelocity.x *= mFriction;
2582 mVelocity.y *= mFriction;
2583 mPrevTime = curTime;
2584 }
2585 };
2586
2587 private static final int ANIM_TAG_KEY = 100;
2588
2589 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2590 return new Runnable() {
2591 @Override
2592 public void run() {
2593 int dragViewIndex = indexOfChild(dragView);
2594
2595 // For each of the pages around the drag view, animate them from the previous
2596 // position to the new position in the layout (as a result of the drag view moving
2597 // in the layout)
2598 // NOTE: We can make an assumption here because we have side-bound pages that we
2599 // will always have pages to animate in from the left
2600 getVisiblePages(mTempVisiblePagesRange);
2601 boundByReorderablePages(true, mTempVisiblePagesRange);
2602 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2603 boolean slideFromLeft = (isLastWidgetPage ||
2604 dragViewIndex > mTempVisiblePagesRange[0]);
2605
2606 // Setup the scroll to the correct page before we swap the views
2607 if (slideFromLeft) {
2608 snapToPageImmediately(dragViewIndex - 1);
2609 }
2610
2611 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2612 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2613 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2614 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2615 ArrayList<Animator> animations = new ArrayList<Animator>();
2616 for (int i = lowerIndex; i <= upperIndex; ++i) {
2617 View v = getChildAt(i);
2618 // dragViewIndex < pageUnderPointIndex, so after we remove the
2619 // drag view all subsequent views to pageUnderPointIndex will
2620 // shift down.
2621 int oldX = 0;
2622 int newX = 0;
2623 if (slideFromLeft) {
2624 if (i == 0) {
2625 // Simulate the page being offscreen with the page spacing
2626 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2627 - mPageSpacing;
2628 } else {
2629 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2630 }
2631 newX = getViewportOffsetX() + getChildOffset(i);
2632 } else {
2633 oldX = getChildOffset(i) - getChildOffset(i - 1);
2634 newX = 0;
2635 }
2636
2637 // Animate the view translation from its old position to its new
2638 // position
2639 AnimatorSet anim = (AnimatorSet) v.getTag();
2640 if (anim != null) {
2641 anim.cancel();
2642 }
2643
2644 // Note: Hacky, but we want to skip any optimizations to not draw completely
2645 // hidden views
2646 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2647 v.setTranslationX(oldX - newX);
2648 anim = new AnimatorSet();
2649 anim.playTogether(
2650 ObjectAnimator.ofFloat(v, "translationX", 0f),
2651 ObjectAnimator.ofFloat(v, "alpha", 1f));
2652 animations.add(anim);
2653 v.setTag(ANIM_TAG_KEY, anim);
2654 }
2655
2656 AnimatorSet slideAnimations = new AnimatorSet();
2657 slideAnimations.playTogether(animations);
2658 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2659 slideAnimations.addListener(new AnimatorListenerAdapter() {
2660 @Override
2661 public void onAnimationEnd(Animator animation) {
2662 final Runnable onCompleteRunnable = new Runnable() {
2663 @Override
2664 public void run() {
2665 mDeferringForDelete = false;
2666 onEndReordering();
2667 onRemoveViewAnimationCompleted();
2668 }
2669 };
2670 zoomIn(onCompleteRunnable);
2671 }
2672 });
2673 slideAnimations.start();
2674
2675 removeView(dragView);
2676 onRemoveView(dragView, true);
2677 }
2678 };
2679 }
2680
2681 public void onFlingToDelete(PointF vel) {
2682 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2683
2684 // NOTE: Because it takes time for the first frame of animation to actually be
2685 // called and we expect the animation to be a continuation of the fling, we have
2686 // to account for the time that has elapsed since the fling finished. And since
2687 // we don't have a startDelay, we will always get call to update when we call
2688 // start() (which we want to ignore).
2689 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2690 private int mCount = -1;
2691 private long mStartTime;
2692 private float mOffset;
2693 /* Anonymous inner class ctor */ {
2694 mStartTime = startTime;
2695 }
2696
2697 @Override
2698 public float getInterpolation(float t) {
2699 if (mCount < 0) {
2700 mCount++;
2701 } else if (mCount == 0) {
2702 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2703 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2704 mCount++;
2705 }
2706 return Math.min(1f, mOffset + t);
2707 }
2708 };
2709
2710 final Rect from = new Rect();
2711 final View dragView = mDragView;
2712 from.left = (int) dragView.getTranslationX();
2713 from.top = (int) dragView.getTranslationY();
2714 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2715 from, startTime, FLING_TO_DELETE_FRICTION);
2716
2717 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2718
2719 // Create and start the animation
2720 ValueAnimator mDropAnim = new ValueAnimator();
2721 mDropAnim.setInterpolator(tInterpolator);
2722 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2723 mDropAnim.setFloatValues(0f, 1f);
2724 mDropAnim.addUpdateListener(updateCb);
2725 mDropAnim.addListener(new AnimatorListenerAdapter() {
2726 public void onAnimationEnd(Animator animation) {
2727 onAnimationEndRunnable.run();
2728 }
2729 });
2730 mDropAnim.start();
2731 mDeferringForDelete = true;
2732 }
2733
2734 /* Drag to delete */
2735 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2736 if (mDeleteDropTarget != null) {
2737 mAltTmpRect.set(0, 0, 0, 0);
2738 View parent = (View) mDeleteDropTarget.getParent();
2739 if (parent != null) {
2740 parent.getGlobalVisibleRect(mAltTmpRect);
2741 }
2742 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2743 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2744 return mTmpRect.contains(x, y);
2745 }
2746 return false;
2747 }
2748
2749 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2750
2751 private void onDropToDelete() {
2752 final View dragView = mDragView;
2753
2754 final float toScale = 0f;
2755 final float toAlpha = 0f;
2756
2757 // Create and start the complex animation
2758 ArrayList<Animator> animations = new ArrayList<Animator>();
2759 AnimatorSet motionAnim = new AnimatorSet();
2760 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2761 motionAnim.playTogether(
2762 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2763 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2764 animations.add(motionAnim);
2765
2766 AnimatorSet alphaAnim = new AnimatorSet();
2767 alphaAnim.setInterpolator(new LinearInterpolator());
2768 alphaAnim.playTogether(
2769 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2770 animations.add(alphaAnim);
2771
2772 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2773
2774 AnimatorSet anim = new AnimatorSet();
2775 anim.playTogether(animations);
2776 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2777 anim.addListener(new AnimatorListenerAdapter() {
2778 public void onAnimationEnd(Animator animation) {
2779 onAnimationEndRunnable.run();
2780 }
2781 });
2782 anim.start();
2783
2784 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002785 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002786
2787 /* Accessibility */
2788 @Override
2789 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2790 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002791 info.setScrollable(getPageCount() > 1);
2792 if (getCurrentPage() < getPageCount() - 1) {
2793 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2794 }
2795 if (getCurrentPage() > 0) {
2796 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2797 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002798 }
2799
2800 @Override
2801 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2802 super.onInitializeAccessibilityEvent(event);
2803 event.setScrollable(true);
2804 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2805 event.setFromIndex(mCurrentPage);
2806 event.setToIndex(mCurrentPage);
2807 event.setItemCount(getChildCount());
2808 }
2809 }
2810
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002811 @Override
2812 public boolean performAccessibilityAction(int action, Bundle arguments) {
2813 if (super.performAccessibilityAction(action, arguments)) {
2814 return true;
2815 }
2816 switch (action) {
2817 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2818 if (getCurrentPage() < getPageCount() - 1) {
2819 scrollRight();
2820 return true;
2821 }
2822 } break;
2823 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2824 if (getCurrentPage() > 0) {
2825 scrollLeft();
2826 return true;
2827 }
2828 } break;
2829 }
2830 return false;
2831 }
2832
Adam Cohen0ffac432013-07-10 11:19:26 -07002833 protected String getCurrentPageDescription() {
2834 return String.format(getContext().getString(R.string.default_scroll_format),
2835 getNextPage() + 1, getChildCount());
2836 }
2837
Winson Chungd11265e2011-08-30 13:37:23 -07002838 @Override
2839 public boolean onHoverEvent(android.view.MotionEvent event) {
2840 return true;
2841 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002842}