blob: 0dbcd97f003bf2cc561467ade109dd15040e346f [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 Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
35import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070036import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070037import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080038import android.view.InputDevice;
39import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070040import android.view.MotionEvent;
41import android.view.VelocityTracker;
42import android.view.View;
43import android.view.ViewConfiguration;
44import android.view.ViewGroup;
45import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070046import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070047import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070049import android.view.animation.AnimationUtils;
50import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080051import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070052import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070053
Winson Chung6a0f57d2011-06-29 20:10:49 -070054import java.util.ArrayList;
55
Winson Chungc58497e2013-09-03 17:48:37 -070056interface Page {
57 public int getPageChildCount();
58 public View getChildOnPageAt(int i);
59 public void removeAllViewsOnPage();
60 public void removeViewOnPageAt(int i);
61 public int indexOfChildOnPage(View v);
62}
63
Winson Chung321e9ee2010-08-09 13:37:56 -070064/**
65 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070066 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070067 */
Michael Jurka8b805b12012-04-18 14:23:14 -070068public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070069 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070070 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070071 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070072
Winson Chung86f77532010-08-24 11:08:22 -070073 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070074 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070075
Adam Cohen7d30a372013-07-01 17:03:59 -070076 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070077 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070078 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070079
Adam Cohenb5ba0972011-09-07 18:02:31 -070080 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070081 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080082
Adam Cohenb64cb5a2011-02-15 13:53:42 -080083 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080084 // The page is moved more than halfway, automatically move to the next page on touch up.
85 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080086
Adam Cohen265b9a62011-12-07 14:37:18 -080087 // The following constants need to be scaled based on density. The scaled versions will be
88 // assigned to the corresponding member variables below.
89 private static final int FLING_THRESHOLD_VELOCITY = 500;
90 private static final int MIN_SNAP_VELOCITY = 1500;
91 private static final int MIN_FLING_VELOCITY = 250;
92
Adam Cohen7d30a372013-07-01 17:03:59 -070093 // We are disabling touch interaction of the widget region for factory ROM.
94 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070095 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070096 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070097
Adam Cohen21cd0022013-10-09 18:57:02 -070098 public static final int INVALID_RESTORE_PAGE = -1001;
99
Adam Cohenf358a4b2013-07-23 16:47:31 -0700100 private boolean mFreeScroll = false;
101 private int mFreeScrollMinScrollX = -1;
102 private int mFreeScrollMaxScrollX = -1;
103
Winson Chung8aad6102012-05-11 16:27:49 -0700104 static final int AUTOMATIC_PAGE_SPACING = -1;
105
Adam Cohen265b9a62011-12-07 14:37:18 -0800106 protected int mFlingThresholdVelocity;
107 protected int mMinFlingVelocity;
108 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700109
Adam Cohenb5ba0972011-09-07 18:02:31 -0700110 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected float mSmoothingTime;
112 protected float mTouchX;
113
114 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700115 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700116
117 protected int mCurrentPage;
Adam Cohen21cd0022013-10-09 18:57:02 -0700118 protected int mRestorePage = INVALID_RESTORE_PAGE;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700119 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700120
Michael Jurka0142d492010-08-25 17:46:15 -0700121 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800122 protected int mMaxScrollX;
Adam Cohenf9618852013-11-08 06:45:03 -0800123 protected LauncherScroller mScroller;
124 private Interpolator mDefaultInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -0700125 private VelocityTracker mVelocityTracker;
Adam Cohen3b185e22013-10-29 14:45:58 -0700126 private int mPageSpacing = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -0700127
Adam Cohen7d30a372013-07-01 17:03:59 -0700128 private float mParentDownMotionX;
129 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700130 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700131 private float mDownMotionY;
132 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700133 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800134 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800135 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800136 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800137 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700138 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700139
Adam Cohendbdff6b2013-09-18 19:09:15 -0700140 private boolean mCancelTap;
141
Adam Cohenedb40762013-07-18 16:45:45 -0700142 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700143
Michael Jurka0142d492010-08-25 17:46:15 -0700144 protected final static int TOUCH_STATE_REST = 0;
145 protected final static int TOUCH_STATE_SCROLLING = 1;
146 protected final static int TOUCH_STATE_PREV_PAGE = 2;
147 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700148 protected final static int TOUCH_STATE_REORDERING = 4;
149
Adam Cohene45440e2010-10-14 18:33:38 -0700150 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700151
Michael Jurka0142d492010-08-25 17:46:15 -0700152 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700153 protected boolean mForceScreenScrolled = false;
Adam Cohencae7f572013-11-04 14:42:52 -0800154
Michael Jurka0142d492010-08-25 17:46:15 -0700155 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700156
Michael Jurka7426c422010-11-11 15:23:47 -0800157 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700158 private int mPagingTouchSlop;
159 private int mMaximumVelocity;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700160 protected int mPageLayoutWidthGap;
161 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700162 protected int mCellCountX = 0;
163 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700164 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800165 protected boolean mAllowOverScroll = true;
166 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800167 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700168 protected boolean mForceDrawAllChildrenNextFrame;
Adam Cohen1d3d4f12014-08-14 19:14:52 -0700169 private boolean mSpacePagesAutomatically = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
Michael Jurka8b805b12012-04-18 14:23:14 -0700171 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800172 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
173 // the screens from continuing to translate beyond the normal bounds.
174 protected int mOverScrollX;
175
Michael Jurka5f1c5092010-09-03 14:15:02 -0700176 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700177
Michael Jurka5f1c5092010-09-03 14:15:02 -0700178 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700179
Winson Chung86f77532010-08-24 11:08:22 -0700180 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700181
Michael Jurkae326f182011-11-21 14:05:46 -0800182 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700183
Michael Jurka0142d492010-08-25 17:46:15 -0700184 // If true, syncPages and syncPageItems will be called to refresh pages
185 protected boolean mContentIsRefreshable = true;
186
187 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700188 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700189
190 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
191 // to switch to a new page
192 protected boolean mUsePagingTouchSlop = true;
193
Michael Jurka8b805b12012-04-18 14:23:14 -0700194 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700195 // (SmoothPagedView does this)
196 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700197 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700198
Patrick Dubroy1262e362010-10-06 15:49:50 -0700199 protected boolean mIsPageMoving = false;
200
Winson Chungf0ea4d32011-06-06 14:27:16 -0700201 // All syncs and layout passes are deferred until data is ready.
202 protected boolean mIsDataReady = false;
203
Adam Cohen7d30a372013-07-01 17:03:59 -0700204 protected boolean mAllowLongPress = true;
205
Winson Chungd2be3812013-07-16 11:11:32 -0700206 // Page Indicator
207 private int mPageIndicatorViewId;
208 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700209 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700210
Adam Cohen7d30a372013-07-01 17:03:59 -0700211 // The viewport whether the pages are to be contained (the actual view may be larger than the
212 // viewport)
213 private Rect mViewport = new Rect();
214
215 // Reordering
216 // We use the min scale to determine how much to expand the actually PagedView measured
217 // dimensions such that when we are zoomed out, the view is not clipped
218 private int REORDERING_DROP_REPOSITION_DURATION = 200;
219 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
220 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700221 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700222 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700223 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700224 protected View mDragView;
225 protected AnimatorSet mZoomInOutAnim;
226 private Runnable mSidePageHoverRunnable;
227 private int mSidePageHoverIndex = -1;
228 // This variable's scope is only for the duration of startReordering() and endReordering()
229 private boolean mReorderingStarted = false;
230 // This variable's scope is for the duration of startReordering() and after the zoomIn()
231 // animation after endReordering()
232 private boolean mIsReordering;
233 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
234 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
235 private int mPostReorderingPreZoomInRemainingAnimationCount;
236 private Runnable mPostReorderingPreZoomInRunnable;
237
Adam Cohen7d30a372013-07-01 17:03:59 -0700238 // Convenience/caching
239 private Matrix mTmpInvMatrix = new Matrix();
240 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700241 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700242 private Rect mTmpRect = new Rect();
243 private Rect mAltTmpRect = new Rect();
244
245 // Fling to delete
246 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
247 private float FLING_TO_DELETE_FRICTION = 0.035f;
248 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
249 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
250 protected int mFlingToDeleteThresholdVelocity = -1400;
251 // Drag to delete
252 private boolean mDeferringForDelete = false;
253 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
254 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
255
256 // Drop to delete
257 private View mDeleteDropTarget;
258
Adam Cohen7d30a372013-07-01 17:03:59 -0700259 // Bouncer
260 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700261
John Spurlock77e1f472013-09-11 10:09:51 -0400262 protected final Rect mInsets = new Rect();
263
Winson Chung86f77532010-08-24 11:08:22 -0700264 public interface PageSwitchListener {
265 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700266 }
267
Winson Chung321e9ee2010-08-09 13:37:56 -0700268 public PagedView(Context context) {
269 this(context, null);
270 }
271
272 public PagedView(Context context, AttributeSet attrs) {
273 this(context, attrs, 0);
274 }
275
276 public PagedView(Context context, AttributeSet attrs, int defStyle) {
277 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700278
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 TypedArray a = context.obtainStyledAttributes(attrs,
280 R.styleable.PagedView, defStyle, 0);
Adam Cohen0cd0eba2013-10-28 14:22:25 -0700281
Winson Chungdf4b83d2010-10-20 17:49:27 -0700282 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700283 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700284 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700285 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700286 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700287 a.recycle();
288
Winson Chung321e9ee2010-08-09 13:37:56 -0700289 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700290 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700291 }
292
293 /**
294 * Initializes various states for this workspace.
295 */
Michael Jurka0142d492010-08-25 17:46:15 -0700296 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700297 mDirtyPageContent = new ArrayList<Boolean>();
298 mDirtyPageContent.ensureCapacity(32);
Adam Cohenf9618852013-11-08 06:45:03 -0800299 mScroller = new LauncherScroller(getContext());
300 setDefaultInterpolator(new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700301 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700302 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700303
304 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700305 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700306 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
307 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700308 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800309
Adam Cohen7d30a372013-07-01 17:03:59 -0700310 // Scale the fling-to-delete threshold by the density
311 mFlingToDeleteThresholdVelocity =
312 (int) (mFlingToDeleteThresholdVelocity * mDensity);
313
Adam Cohen265b9a62011-12-07 14:37:18 -0800314 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
315 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
316 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700317 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700318 }
319
Adam Cohenf9618852013-11-08 06:45:03 -0800320 protected void setDefaultInterpolator(Interpolator interpolator) {
321 mDefaultInterpolator = interpolator;
322 mScroller.setInterpolator(mDefaultInterpolator);
323 }
324
Winson Chungd2be3812013-07-16 11:11:32 -0700325 protected void onAttachedToWindow() {
Adam Cohen53805212013-10-01 10:39:23 -0700326 super.onAttachedToWindow();
327
Winson Chungd2be3812013-07-16 11:11:32 -0700328 // Hook up the page indicator
329 ViewGroup parent = (ViewGroup) getParent();
Adam Cohen9bfdb762014-07-21 17:44:06 -0700330 ViewGroup grandParent = (ViewGroup) parent.getParent();
Winson Chungd2be3812013-07-16 11:11:32 -0700331 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
Adam Cohen9bfdb762014-07-21 17:44:06 -0700332 mPageIndicator = (PageIndicator) grandParent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700333 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700334
Winson Chung7819a562013-09-19 15:55:45 -0700335 ArrayList<PageIndicator.PageMarkerResources> markers =
336 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700337 for (int i = 0; i < getChildCount(); ++i) {
338 markers.add(getPageIndicatorMarker(i));
339 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700340
Winson Chungc58497e2013-09-03 17:48:37 -0700341 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenfbdf4272013-10-09 13:02:21 -0700342
343 OnClickListener listener = getPageIndicatorClickListener();
344 if (listener != null) {
345 mPageIndicator.setOnClickListener(listener);
346 }
Adam Cohen53805212013-10-01 10:39:23 -0700347 mPageIndicator.setContentDescription(getPageIndicatorDescription());
Winson Chungd2be3812013-07-16 11:11:32 -0700348 }
349 }
350
Adam Cohen53805212013-10-01 10:39:23 -0700351 protected String getPageIndicatorDescription() {
352 return getCurrentPageDescription();
353 }
354
355 protected OnClickListener getPageIndicatorClickListener() {
356 return null;
357 }
358
Winson Chungd2be3812013-07-16 11:11:32 -0700359 protected void onDetachedFromWindow() {
360 // Unhook the page indicator
361 mPageIndicator = null;
362 }
363
Adam Cohen7d30a372013-07-01 17:03:59 -0700364 void setDeleteDropTarget(View v) {
365 mDeleteDropTarget = v;
366 }
367
368 // Convenience methods to map points from self to parent and vice versa
369 float[] mapPointFromViewToParent(View v, float x, float y) {
370 mTmpPoint[0] = x;
371 mTmpPoint[1] = y;
372 v.getMatrix().mapPoints(mTmpPoint);
373 mTmpPoint[0] += v.getLeft();
374 mTmpPoint[1] += v.getTop();
375 return mTmpPoint;
376 }
377 float[] mapPointFromParentToView(View v, float x, float y) {
378 mTmpPoint[0] = x - v.getLeft();
379 mTmpPoint[1] = y - v.getTop();
380 v.getMatrix().invert(mTmpInvMatrix);
381 mTmpInvMatrix.mapPoints(mTmpPoint);
382 return mTmpPoint;
383 }
384
385 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700386 if (mDragView != null) {
387 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
388 (mDragViewBaselineLeft - mDragView.getLeft());
389 float y = mLastMotionY - mDownMotionY;
390 mDragView.setTranslationX(x);
391 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700392
Adam Cohenf358a4b2013-07-23 16:47:31 -0700393 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
394 + x + ", " + y);
395 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700396 }
397
398 public void setMinScale(float f) {
399 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700400 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700401 requestLayout();
402 }
403
404 @Override
405 public void setScaleX(float scaleX) {
406 super.setScaleX(scaleX);
407 if (isReordering(true)) {
408 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
409 mLastMotionX = p[0];
410 mLastMotionY = p[1];
411 updateDragViewTranslationDuringDrag();
412 }
413 }
414
415 // Convenience methods to get the actual width/height of the PagedView (since it is measured
416 // to be larger to account for the minimum possible scale)
417 int getViewportWidth() {
418 return mViewport.width();
419 }
420 int getViewportHeight() {
421 return mViewport.height();
422 }
423
424 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
425 // PagedView both horizontally and vertically
426 int getViewportOffsetX() {
427 return (getMeasuredWidth() - getViewportWidth()) / 2;
428 }
429
430 int getViewportOffsetY() {
431 return (getMeasuredHeight() - getViewportHeight()) / 2;
432 }
433
Adam Cohenedb40762013-07-18 16:45:45 -0700434 PageIndicator getPageIndicator() {
435 return mPageIndicator;
436 }
Winson Chung7819a562013-09-19 15:55:45 -0700437 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
438 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700439 }
Adam Cohenedb40762013-07-18 16:45:45 -0700440
Adam Cohen674531f2013-12-13 15:07:14 -0800441 /**
442 * Add a page change listener which will be called when a page is _finished_ listening.
443 *
444 */
Winson Chung86f77532010-08-24 11:08:22 -0700445 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
446 mPageSwitchListener = pageSwitchListener;
447 if (mPageSwitchListener != null) {
448 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700449 }
450 }
451
452 /**
Winson Chung52aee602013-01-30 12:01:02 -0800453 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
454 */
455 public boolean isLayoutRtl() {
456 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
457 }
458
459 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700460 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
461 * out pages.
462 */
463 protected void setDataIsReady() {
464 mIsDataReady = true;
465 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700466
Winson Chungf0ea4d32011-06-06 14:27:16 -0700467 protected boolean isDataReady() {
468 return mIsDataReady;
469 }
470
471 /**
Winson Chung86f77532010-08-24 11:08:22 -0700472 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700473 *
Winson Chung86f77532010-08-24 11:08:22 -0700474 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700475 */
Winson Chung86f77532010-08-24 11:08:22 -0700476 int getCurrentPage() {
477 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700478 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700479
Winson Chung360e63f2012-04-27 13:48:05 -0700480 int getNextPage() {
481 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
482 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700483
Winson Chung86f77532010-08-24 11:08:22 -0700484 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700485 return getChildCount();
486 }
487
Winson Chung86f77532010-08-24 11:08:22 -0700488 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700489 return getChildAt(index);
490 }
491
Adam Cohenae4f1552011-10-20 00:15:42 -0700492 protected int indexToPage(int index) {
493 return index;
494 }
495
Winson Chung321e9ee2010-08-09 13:37:56 -0700496 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800497 * Updates the scroll of the current page immediately to its final scroll position. We use this
498 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
499 * the previous tab page.
500 */
501 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700502 // If the current page is invalid, just reset the scroll position to zero
503 int newX = 0;
504 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700505 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700506 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800507 scrollTo(newX, 0);
508 mScroller.setFinalX(newX);
Adam Cohen4fe4c932013-10-28 16:02:34 -0700509 forceFinishScroller();
Winson Chungbbc60d82010-11-11 16:34:41 -0800510 }
511
512 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700513 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
Adam Cohen4fe4c932013-10-28 16:02:34 -0700514 * {@link #updateCurrentPageScroll()} should be called, to correctly set the final state and
515 * re-enable scrolling.
Chet Haasebc2f0822012-10-26 17:59:53 -0700516 */
Adam Cohen4fe4c932013-10-28 16:02:34 -0700517 void stopScrolling() {
Winson Chungb88ae412013-10-29 17:21:56 -0700518 mCurrentPage = getNextPage();
Adam Cohen674531f2013-12-13 15:07:14 -0800519 notifyPageSwitchListener();
Adam Cohen4fe4c932013-10-28 16:02:34 -0700520 forceFinishScroller();
Chet Haasebc2f0822012-10-26 17:59:53 -0700521 }
522
Adam Cohen8bdbaab2013-10-29 15:25:02 -0700523 private void abortScrollerAnimation(boolean resetNextPage) {
Adam Cohen4fe4c932013-10-28 16:02:34 -0700524 mScroller.abortAnimation();
525 // We need to clean up the next page here to avoid computeScrollHelper from
526 // updating current page on the pass.
Adam Cohen8bdbaab2013-10-29 15:25:02 -0700527 if (resetNextPage) {
528 mNextPage = INVALID_PAGE;
529 }
Chet Haasebc2f0822012-10-26 17:59:53 -0700530 }
Adam Cohen4fe4c932013-10-28 16:02:34 -0700531
532 private void forceFinishScroller() {
533 mScroller.forceFinished(true);
534 // We need to clean up the next page here to avoid computeScrollHelper from
535 // updating current page on the pass.
536 mNextPage = INVALID_PAGE;
537 }
538
Adam Cohen6f127a62014-06-12 14:54:41 -0700539 private int validateNewPage(int newPage) {
540 int validatedPage = newPage;
541 // When in free scroll mode, we need to clamp to the free scroll page range.
542 if (mFreeScroll) {
543 getFreeScrollPageRange(mTempVisiblePagesRange);
544 validatedPage = Math.max(mTempVisiblePagesRange[0],
545 Math.min(newPage, mTempVisiblePagesRange[1]));
546 }
547 // Ensure that it is clamped by the actual set of children in all cases
548 validatedPage = Math.max(0, Math.min(validatedPage, getPageCount() - 1));
549 return validatedPage;
550 }
551
Chet Haasebc2f0822012-10-26 17:59:53 -0700552 /**
Winson Chung86f77532010-08-24 11:08:22 -0700553 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700554 */
Winson Chung86f77532010-08-24 11:08:22 -0700555 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800556 if (!mScroller.isFinished()) {
Adam Cohen8bdbaab2013-10-29 15:25:02 -0700557 abortScrollerAnimation(true);
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800558 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800559 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
560 // the default
561 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800562 return;
563 }
Adam Cohene61a9a22013-06-11 15:45:31 -0700564 mForceScreenScrolled = true;
Adam Cohen6f127a62014-06-12 14:54:41 -0700565 mCurrentPage = validateNewPage(currentPage);
Winson Chung181c3dc2013-07-17 15:36:20 -0700566 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700567 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800568 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700569 }
570
Winson Chung8c87cd82013-07-23 16:20:10 -0700571 /**
572 * The restore page will be set in place of the current page at the next (likely first)
573 * layout.
574 */
575 void setRestorePage(int restorePage) {
576 mRestorePage = restorePage;
577 }
Winson Chung9b9fb962013-11-15 15:39:34 -0800578 int getRestorePage() {
579 return mRestorePage;
580 }
Winson Chung8c87cd82013-07-23 16:20:10 -0700581
Adam Cohen674531f2013-12-13 15:07:14 -0800582 /**
583 * Should be called whenever the page changes. In the case of a scroll, we wait until the page
584 * has settled.
585 */
Michael Jurka0142d492010-08-25 17:46:15 -0700586 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700587 if (mPageSwitchListener != null) {
Adam Cohen674531f2013-12-13 15:07:14 -0800588 mPageSwitchListener.onPageSwitch(getPageAt(getNextPage()), getNextPage());
Winson Chung321e9ee2010-08-09 13:37:56 -0700589 }
Winson Chungd2be3812013-07-16 11:11:32 -0700590
Adam Cohen674531f2013-12-13 15:07:14 -0800591 updatePageIndicator();
592 }
593
594 private void updatePageIndicator() {
Winson Chungd2be3812013-07-16 11:11:32 -0700595 // Update the page indicator (when we aren't reordering)
596 if (mPageIndicator != null && !isReordering(false)) {
597 mPageIndicator.setActiveMarker(getNextPage());
598 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700599 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800600 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700601 if (!mIsPageMoving) {
602 mIsPageMoving = true;
603 onPageBeginMoving();
604 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700605 }
606
Michael Jurkace7e05f2011-02-01 22:02:35 -0800607 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700608 if (mIsPageMoving) {
609 mIsPageMoving = false;
610 onPageEndMoving();
611 }
Michael Jurka0142d492010-08-25 17:46:15 -0700612 }
613
Adam Cohen26976d92011-03-22 15:33:33 -0700614 protected boolean isPageMoving() {
615 return mIsPageMoving;
616 }
617
Michael Jurka0142d492010-08-25 17:46:15 -0700618 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700619 protected void onPageBeginMoving() {
620 }
621
622 // a method that subclasses can override to add behavior
623 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700624 }
625
Winson Chung321e9ee2010-08-09 13:37:56 -0700626 /**
Winson Chung86f77532010-08-24 11:08:22 -0700627 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700628 *
629 * @param l The listener used to respond to long clicks.
630 */
631 @Override
632 public void setOnLongClickListener(OnLongClickListener l) {
633 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700634 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700635 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700636 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700637 }
Adam Cohen1697b792013-09-17 19:08:21 -0700638 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700639 }
640
641 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800642 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700643 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800644 }
645
646 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700647 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700648 // In free scroll mode, we clamp the scrollX
649 if (mFreeScroll) {
650 x = Math.min(x, mFreeScrollMaxScrollX);
651 x = Math.max(x, mFreeScrollMinScrollX);
652 }
653
Adam Cohen0ffac432013-07-10 11:19:26 -0700654 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800655 mUnboundedScrollX = x;
656
Adam Cohen0ffac432013-07-10 11:19:26 -0700657 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
658 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
659 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800660 super.scrollTo(0, y);
661 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700662 if (isRtl) {
663 overScroll(x - mMaxScrollX);
664 } else {
665 overScroll(x);
666 }
Adam Cohen68d73932010-11-15 10:50:58 -0800667 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700668 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800669 super.scrollTo(mMaxScrollX, y);
670 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700671 if (isRtl) {
672 overScroll(x);
673 } else {
674 overScroll(x - mMaxScrollX);
675 }
Adam Cohen68d73932010-11-15 10:50:58 -0800676 }
677 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800678 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800679 super.scrollTo(x, y);
680 }
681
Michael Jurka0142d492010-08-25 17:46:15 -0700682 mTouchX = x;
683 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700684
685 // Update the last motion events when scrolling
686 if (isReordering(true)) {
687 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
688 mLastMotionX = p[0];
689 mLastMotionY = p[1];
690 updateDragViewTranslationDuringDrag();
691 }
Michael Jurka0142d492010-08-25 17:46:15 -0700692 }
693
Adam Cohen53805212013-10-01 10:39:23 -0700694 private void sendScrollAccessibilityEvent() {
695 AccessibilityManager am =
696 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
697 if (am.isEnabled()) {
698 AccessibilityEvent ev =
699 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
Adam Cohen53805212013-10-01 10:39:23 -0700700 ev.setItemCount(getChildCount());
701 ev.setFromIndex(mCurrentPage);
Adam Cohene4602ae2013-10-31 15:46:45 -0700702 ev.setToIndex(getNextPage());
Adam Cohen53805212013-10-01 10:39:23 -0700703
Alan Viverette254139a2013-10-08 13:13:46 -0700704 final int action;
Adam Cohen53805212013-10-01 10:39:23 -0700705 if (getNextPage() >= mCurrentPage) {
706 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD;
707 } else {
708 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
709 }
710
711 ev.setAction(action);
712 sendAccessibilityEventUnchecked(ev);
713 }
714 }
715
Michael Jurka0142d492010-08-25 17:46:15 -0700716 // we moved this functionality to a helper function so SmoothPagedView can reuse it
717 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700718 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700719 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700720 if (getScrollX() != mScroller.getCurrX()
721 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700722 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700723 float scaleX = mFreeScroll ? getScaleX() : 1f;
724 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
725 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700726 }
Michael Jurka0142d492010-08-25 17:46:15 -0700727 invalidate();
728 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700729 } else if (mNextPage != INVALID_PAGE) {
Adam Cohen53805212013-10-01 10:39:23 -0700730 sendScrollAccessibilityEvent();
731
Adam Cohen6f127a62014-06-12 14:54:41 -0700732 mCurrentPage = validateNewPage(mNextPage);
Winson Chung86f77532010-08-24 11:08:22 -0700733 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700734 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700735
Winson Chung9c0565f2013-07-19 13:49:06 -0700736 // Load the associated pages if necessary
737 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
738 loadAssociatedPages(mCurrentPage);
739 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
740 }
741
Adam Cohen73aa9752010-11-24 16:26:58 -0800742 // We don't want to trigger a page end moving unless the page has settled
743 // and the user has stopped scrolling
744 if (mTouchState == TOUCH_STATE_REST) {
745 pageEndMoving();
746 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700747
Adam Cohen7d30a372013-07-01 17:03:59 -0700748 onPostReorderingAnimationCompleted();
Adam Cohen53805212013-10-01 10:39:23 -0700749 AccessibilityManager am = (AccessibilityManager)
Adam Cohen0ffac432013-07-10 11:19:26 -0700750 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
Adam Cohen53805212013-10-01 10:39:23 -0700751 if (am.isEnabled()) {
752 // Notify the user when the page changes
753 announceForAccessibility(getCurrentPageDescription());
Adam Cohen0ffac432013-07-10 11:19:26 -0700754 }
Michael Jurka0142d492010-08-25 17:46:15 -0700755 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700756 }
Michael Jurka0142d492010-08-25 17:46:15 -0700757 return false;
758 }
759
760 @Override
761 public void computeScroll() {
762 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700763 }
764
Adam Cohen7d30a372013-07-01 17:03:59 -0700765 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
766 return mTopAlignPageWhenShrinkingForBouncer;
767 }
768
Adam Cohen96d30a12013-07-16 18:13:21 -0700769 public static class LayoutParams extends ViewGroup.LayoutParams {
770 public boolean isFullScreenPage = false;
771
772 /**
773 * {@inheritDoc}
774 */
775 public LayoutParams(int width, int height) {
776 super(width, height);
777 }
778
779 public LayoutParams(ViewGroup.LayoutParams source) {
780 super(source);
781 }
782 }
783
784 protected LayoutParams generateDefaultLayoutParams() {
785 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
786 }
787
Adam Cohenedb40762013-07-18 16:45:45 -0700788 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700789 LayoutParams lp = generateDefaultLayoutParams();
790 lp.isFullScreenPage = true;
791 super.addView(page, 0, lp);
792 }
793
Adam Cohen410f3cd2013-09-22 12:09:32 -0700794 public int getNormalChildHeight() {
795 return mNormalChildHeight;
796 }
797
Winson Chung321e9ee2010-08-09 13:37:56 -0700798 @Override
799 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700800 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700801 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
802 return;
803 }
804
Adam Cohen7d30a372013-07-01 17:03:59 -0700805 // We measure the dimensions of the PagedView to be larger than the pages so that when we
806 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700807 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
808 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
809 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700810 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Winson Chungc82d2622013-11-06 13:23:29 -0800811 // NOTE: We multiply by 2f to account for the fact that depending on the offset of the
Adam Cohen7d30a372013-07-01 17:03:59 -0700812 // viewport, we can be at most one and a half screens offset once we scale down
813 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohen3b185e22013-10-29 14:45:58 -0700814 int maxSize = Math.max(dm.widthPixels + mInsets.left + mInsets.right,
815 dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700816
Winson Chungc82d2622013-11-06 13:23:29 -0800817 int parentWidthSize = (int) (2f * maxSize);
818 int parentHeightSize = (int) (2f * maxSize);
Winson Chungc58497e2013-09-03 17:48:37 -0700819 int scaledWidthSize, scaledHeightSize;
820 if (mUseMinScale) {
Winson Chungc58497e2013-09-03 17:48:37 -0700821 scaledWidthSize = (int) (parentWidthSize / mMinScale);
822 scaledHeightSize = (int) (parentHeightSize / mMinScale);
823 } else {
824 scaledWidthSize = widthSize;
825 scaledHeightSize = heightSize;
826 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700827 mViewport.set(0, 0, widthSize, heightSize);
828
829 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
830 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
831 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700832 }
833
Winson Chung8aad6102012-05-11 16:27:49 -0700834 // Return early if we aren't given a proper dimension
835 if (widthSize <= 0 || heightSize <= 0) {
836 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
837 return;
838 }
839
Adam Lesinski6b879f02010-11-04 16:15:23 -0700840 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
841 * of the All apps view on XLarge displays to not take up more space then it needs. Width
842 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
843 * each page to have the same width.
844 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700845 final int verticalPadding = getPaddingTop() + getPaddingBottom();
846 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700847
Adam Cohen1d3d4f12014-08-14 19:14:52 -0700848 int referenceChildWidth = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -0700849 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700850 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700851 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700852 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
853 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
854 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
855 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700856 final int childCount = getChildCount();
857 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700858 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700859 final View child = getPageAt(i);
Vladimir Marko2824b072013-10-04 16:42:17 +0100860 if (child.getVisibility() != GONE) {
861 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700862
Vladimir Marko2824b072013-10-04 16:42:17 +0100863 int childWidthMode;
864 int childHeightMode;
865 int childWidth;
866 int childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700867
Vladimir Marko2824b072013-10-04 16:42:17 +0100868 if (!lp.isFullScreenPage) {
869 if (lp.width == LayoutParams.WRAP_CONTENT) {
870 childWidthMode = MeasureSpec.AT_MOST;
871 } else {
872 childWidthMode = MeasureSpec.EXACTLY;
873 }
874
875 if (lp.height == LayoutParams.WRAP_CONTENT) {
876 childHeightMode = MeasureSpec.AT_MOST;
877 } else {
878 childHeightMode = MeasureSpec.EXACTLY;
879 }
880
Adam Cohen3b185e22013-10-29 14:45:58 -0700881 childWidth = getViewportWidth() - horizontalPadding
882 - mInsets.left - mInsets.right;
883 childHeight = getViewportHeight() - verticalPadding
884 - mInsets.top - mInsets.bottom;
Vladimir Marko2824b072013-10-04 16:42:17 +0100885 mNormalChildHeight = childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700886 } else {
887 childWidthMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700888 childHeightMode = MeasureSpec.EXACTLY;
Vladimir Marko2824b072013-10-04 16:42:17 +0100889
Adam Cohen3b185e22013-10-29 14:45:58 -0700890 childWidth = getViewportWidth() - mInsets.left - mInsets.right;
891 childHeight = getViewportHeight();
Adam Cohen96d30a12013-07-16 18:13:21 -0700892 }
Adam Cohen1d3d4f12014-08-14 19:14:52 -0700893 if (referenceChildWidth == 0) {
894 referenceChildWidth = childWidth;
895 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700896
Vladimir Marko2824b072013-10-04 16:42:17 +0100897 final int childWidthMeasureSpec =
898 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
899 final int childHeightMeasureSpec =
900 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
901 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700902 }
Adam Lesinski6b879f02010-11-04 16:15:23 -0700903 }
Adam Cohen1d3d4f12014-08-14 19:14:52 -0700904 if (mSpacePagesAutomatically) {
905 int spacing = (getViewportWidth() - mInsets.left - mInsets.right
906 - referenceChildWidth) / 2;
907 if (spacing >= 0) {
908 setPageSpacing(spacing);
909 }
910 mSpacePagesAutomatically = false;
911 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700912 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Adam Cohen60b07122011-11-14 17:26:06 -0800913 }
914
Adam Cohen1d3d4f12014-08-14 19:14:52 -0700915 /**
916 * This method should be called once before first layout / measure pass.
917 */
918 protected void setSinglePageInViewport() {
919 mSpacePagesAutomatically = true;
920 }
921
Winson Chung321e9ee2010-08-09 13:37:56 -0700922 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700923 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700924 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700925 return;
926 }
927
Winson Chung785d2eb2011-04-14 16:08:02 -0700928 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700929 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700930
Adam Cohen7d30a372013-07-01 17:03:59 -0700931 int offsetX = getViewportOffsetX();
932 int offsetY = getViewportOffsetY();
933
934 // Update the viewport offsets
935 mViewport.offset(offsetX, offsetY);
936
Adam Cohen0ffac432013-07-10 11:19:26 -0700937 final boolean isRtl = isLayoutRtl();
938
939 final int startIndex = isRtl ? childCount - 1 : 0;
940 final int endIndex = isRtl ? -1 : childCount;
941 final int delta = isRtl ? -1 : 1;
942
Adam Cohen7d30a372013-07-01 17:03:59 -0700943 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700944
Adam Cohen3b185e22013-10-29 14:45:58 -0700945 LayoutParams lp = (LayoutParams) getChildAt(startIndex).getLayoutParams();
Adam Cohen84a465a2013-11-11 18:49:56 +0000946 LayoutParams nextLp;
Adam Cohen3b185e22013-10-29 14:45:58 -0700947
948 int childLeft = offsetX + (lp.isFullScreenPage ? 0 : getPaddingLeft());
Adam Cohenedb40762013-07-18 16:45:45 -0700949 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
950 mPageScrolls = new int[getChildCount()];
951 }
952
Adam Cohen0ffac432013-07-10 11:19:26 -0700953 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700954 final View child = getPageAt(i);
Winson Chung321e9ee2010-08-09 13:37:56 -0700955 if (child.getVisibility() != View.GONE) {
Adam Cohen3b185e22013-10-29 14:45:58 -0700956 lp = (LayoutParams) child.getLayoutParams();
Vladimir Marko2824b072013-10-04 16:42:17 +0100957 int childTop;
958 if (lp.isFullScreenPage) {
959 childTop = offsetY;
960 } else {
961 childTop = offsetY + getPaddingTop() + mInsets.top;
962 if (mCenterPagesVertically) {
963 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
964 }
965 }
966
Adam Cohen96d30a12013-07-16 18:13:21 -0700967 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700968 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800969
Winson Chung785d2eb2011-04-14 16:08:02 -0700970 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700971 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800972 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700973
Adam Cohen3b185e22013-10-29 14:45:58 -0700974 int scrollOffsetLeft = lp.isFullScreenPage ? 0 : getPaddingLeft();
975 mPageScrolls[i] = childLeft - scrollOffsetLeft - offsetX;
Adam Cohen84a465a2013-11-11 18:49:56 +0000976
977 int pageGap = mPageSpacing;
978 int next = i + delta;
979 if (next != endIndex) {
980 nextLp = (LayoutParams) getPageAt(next).getLayoutParams();
981 } else {
982 nextLp = null;
983 }
984
985 // Prevent full screen pages from showing in the viewport
986 // when they are not the current page.
987 if (lp.isFullScreenPage) {
988 pageGap = getPaddingLeft();
989 } else if (nextLp != null && nextLp.isFullScreenPage) {
990 pageGap = getPaddingRight();
991 }
992
993 childLeft += childWidth + pageGap;
Winson Chung321e9ee2010-08-09 13:37:56 -0700994 }
995 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700996
997 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
998 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800999 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -07001000 setHorizontalScrollBarEnabled(true);
1001 mFirstLayout = false;
1002 }
Adam Cohenf698c6e2013-07-17 18:44:25 -07001003
1004 if (childCount > 0) {
1005 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -07001006 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -07001007 } else {
1008 mMaxScrollX = 0;
1009 }
1010
1011 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
1012 !mDeferringForDelete) {
Adam Cohen21cd0022013-10-09 18:57:02 -07001013 if (mRestorePage != INVALID_RESTORE_PAGE) {
Winson Chung8c87cd82013-07-23 16:20:10 -07001014 setCurrentPage(mRestorePage);
Adam Cohen21cd0022013-10-09 18:57:02 -07001015 mRestorePage = INVALID_RESTORE_PAGE;
Winson Chung8c87cd82013-07-23 16:20:10 -07001016 } else {
1017 setCurrentPage(getNextPage());
1018 }
Adam Cohenf698c6e2013-07-17 18:44:25 -07001019 }
1020 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -07001021
1022 if (isReordering(true)) {
1023 updateDragViewTranslationDuringDrag();
1024 }
Winson Chunge3193b92010-09-10 11:44:42 -07001025 }
1026
Adam Cohen3b185e22013-10-29 14:45:58 -07001027 public void setPageSpacing(int pageSpacing) {
1028 mPageSpacing = pageSpacing;
1029 requestLayout();
1030 }
1031
Adam Cohenf34bab52010-09-30 14:11:56 -07001032 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -07001033 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1034
1035 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -07001036 for (int i = 0; i < getChildCount(); i++) {
1037 View child = getChildAt(i);
1038 if (child != null) {
1039 float scrollProgress = getScrollProgress(screenCenter, child, i);
1040 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -08001041 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -07001042 }
1043 }
1044 invalidate();
1045 }
Adam Cohenf34bab52010-09-30 14:11:56 -07001046 }
1047
Winson Chungc58497e2013-09-03 17:48:37 -07001048 protected void enablePagedViewAnimations() {
1049 mAllowPagedViewAnimations = true;
1050
1051 }
1052 protected void disablePagedViewAnimations() {
1053 mAllowPagedViewAnimations = false;
1054 }
1055
Winson Chunge3193b92010-09-10 11:44:42 -07001056 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -07001057 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -07001058 // Update the page indicator, we don't update the page indicator as we
1059 // add/remove pages
1060 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -07001061 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -07001062 mPageIndicator.addMarker(pageIndex,
1063 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -07001064 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001065 }
1066
Adam Cohen2591f6a2011-10-25 14:36:40 -07001067 // This ensures that when children are added, they get the correct transforms / alphas
1068 // in accordance with any scroll effects.
1069 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001070 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001071 invalidate();
1072 }
1073
Michael Jurka8b805b12012-04-18 14:23:14 -07001074 @Override
1075 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001076 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001077 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001078 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001079 }
1080
Winson Chungd2be3812013-07-16 11:11:32 -07001081 private void removeMarkerForView(int index) {
1082 // Update the page indicator, we don't update the page indicator as we
1083 // add/remove pages
1084 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001085 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001086 }
1087 }
1088
1089 @Override
1090 public void removeView(View v) {
1091 // XXX: We should find a better way to hook into this before the view
1092 // gets removed form its parent...
1093 removeMarkerForView(indexOfChild(v));
1094 super.removeView(v);
1095 }
1096 @Override
1097 public void removeViewInLayout(View v) {
1098 // XXX: We should find a better way to hook into this before the view
1099 // gets removed form its parent...
1100 removeMarkerForView(indexOfChild(v));
1101 super.removeViewInLayout(v);
1102 }
1103 @Override
1104 public void removeViewAt(int index) {
1105 // XXX: We should find a better way to hook into this before the view
1106 // gets removed form its parent...
1107 removeViewAt(index);
1108 super.removeViewAt(index);
1109 }
1110 @Override
1111 public void removeAllViewsInLayout() {
1112 // Update the page indicator, we don't update the page indicator as we
1113 // add/remove pages
1114 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001115 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001116 }
1117
1118 super.removeAllViewsInLayout();
1119 }
1120
Adam Cohen73894962011-10-31 13:17:17 -07001121 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001122 if (index < 0 || index > getChildCount() - 1) return 0;
1123
Adam Cohenf698c6e2013-07-17 18:44:25 -07001124 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001125
Adam Cohenf698c6e2013-07-17 18:44:25 -07001126 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001127 }
1128
Adam Cohen6f127a62014-06-12 14:54:41 -07001129 protected void getFreeScrollPageRange(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001130 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001131 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001132 }
1133
Michael Jurkadde558b2011-11-09 22:09:06 -08001134 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001135 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001136 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001137
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001138 range[0] = -1;
1139 range[1] = -1;
1140
Michael Jurkac4fb9172010-09-02 17:19:20 -07001141 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001142 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001143 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001144
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001145 int count = getChildCount();
1146 for (int i = 0; i < count; i++) {
1147 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001148
Winson Chungc9ca2982013-07-19 12:07:38 -07001149 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001150 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001151 if (mTmpIntPoint[0] > viewportWidth) {
1152 if (range[0] == -1) {
1153 continue;
1154 } else {
1155 break;
1156 }
1157 }
1158
Adam Cohen6a678da2013-09-24 10:58:01 -07001159 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001160 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1161 if (mTmpIntPoint[0] < 0) {
1162 if (range[0] == -1) {
1163 continue;
1164 } else {
1165 break;
1166 }
1167 }
1168 curScreen = i;
1169 if (range[0] < 0) {
1170 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001171 }
1172 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001173
1174 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001175 } else {
1176 range[0] = -1;
1177 range[1] = -1;
1178 }
1179 }
1180
Michael Jurka920d7f42012-05-14 16:29:55 -07001181 protected boolean shouldDrawChild(View child) {
Adam Cohen63f1ec02014-08-12 09:23:13 -07001182 return child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001183 }
1184
Michael Jurkadde558b2011-11-09 22:09:06 -08001185 @Override
1186 protected void dispatchDraw(Canvas canvas) {
Michael Jurkadde558b2011-11-09 22:09:06 -08001187 // Find out which screens are visible; as an optimization we only call draw on them
1188 final int pageCount = getChildCount();
1189 if (pageCount > 0) {
Adam Cohen4de09742013-12-12 16:16:39 -08001190 int halfScreenSize = getViewportWidth() / 2;
1191 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1192 // Otherwise it is equal to the scaled overscroll position.
1193 int screenCenter = mOverScrollX + halfScreenSize;
1194
1195 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
1196 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1197 // set it for the next frame
1198 mForceScreenScrolled = false;
1199 screenScrolled(screenCenter);
1200 mLastScreenCenter = screenCenter;
1201 }
1202
Michael Jurkadde558b2011-11-09 22:09:06 -08001203 getVisiblePages(mTempVisiblePagesRange);
1204 final int leftScreen = mTempVisiblePagesRange[0];
1205 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001206 if (leftScreen != -1 && rightScreen != -1) {
1207 final long drawingTime = getDrawingTime();
1208 // Clip to the bounds
1209 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001210 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1211 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001212
Adam Cohen7d30a372013-07-01 17:03:59 -07001213 // Draw all the children, leaving the drag view for last
1214 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001215 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001216 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001217 if (mForceDrawAllChildrenNextFrame ||
1218 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001219 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001220 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001221 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001222 // Draw the drag view on top (if there is one)
1223 if (mDragView != null) {
1224 drawChild(canvas, mDragView, drawingTime);
1225 }
1226
Michael Jurka5e368ff2012-05-14 23:13:15 -07001227 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001228 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001229 }
Michael Jurka0142d492010-08-25 17:46:15 -07001230 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001231 }
1232
1233 @Override
1234 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001235 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001236 if (page != mCurrentPage || !mScroller.isFinished()) {
1237 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001238 return true;
1239 }
1240 return false;
1241 }
1242
1243 @Override
1244 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001245 int focusablePage;
1246 if (mNextPage != INVALID_PAGE) {
1247 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001248 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001249 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001250 }
Winson Chung86f77532010-08-24 11:08:22 -07001251 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001252 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001253 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001254 }
1255 return false;
1256 }
1257
1258 @Override
1259 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001260 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001261 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001262 if (getCurrentPage() > 0) {
1263 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001264 return true;
1265 }
1266 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001267 if (getCurrentPage() < getPageCount() - 1) {
1268 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001269 return true;
1270 }
1271 }
1272 return super.dispatchUnhandledMove(focused, direction);
1273 }
1274
1275 @Override
1276 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001277 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001278 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001279 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001280 }
1281 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001282 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001283 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001284 }
1285 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001286 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001287 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001288 }
1289 }
1290 }
1291
1292 /**
1293 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001294 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001295 *
Winson Chung86f77532010-08-24 11:08:22 -07001296 * This happens when live folders requery, and if they're off page, they
1297 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001298 */
1299 @Override
1300 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001301 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001302 View v = focused;
1303 while (true) {
1304 if (v == current) {
1305 super.focusableViewAvailable(focused);
1306 return;
1307 }
1308 if (v == this) {
1309 return;
1310 }
1311 ViewParent parent = v.getParent();
1312 if (parent instanceof View) {
1313 v = (View)v.getParent();
1314 } else {
1315 return;
1316 }
1317 }
1318 }
1319
1320 /**
1321 * {@inheritDoc}
1322 */
1323 @Override
1324 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1325 if (disallowIntercept) {
1326 // We need to make sure to cancel our long press if
1327 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001328 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001329 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001330 }
1331 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1332 }
1333
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001334 /**
1335 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1336 */
1337 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001338 if (isLayoutRtl()) {
1339 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohen3b185e22013-10-29 14:45:58 -07001340 getPaddingRight() - mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001341 }
Adam Cohen3b185e22013-10-29 14:45:58 -07001342 return (x < getViewportOffsetX() + getPaddingLeft() + mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001343 }
1344
1345 /**
1346 * Return true if a tap at (x, y) should trigger a flip to the next page.
1347 */
1348 protected boolean hitsNextPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001349 if (isLayoutRtl()) {
Adam Cohen3b185e22013-10-29 14:45:58 -07001350 return (x < getViewportOffsetX() + getPaddingLeft() + mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001351 }
1352 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohen3b185e22013-10-29 14:45:58 -07001353 getPaddingRight() - mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001354 }
Winson Chung52aee602013-01-30 12:01:02 -08001355
Adam Cohen7d30a372013-07-01 17:03:59 -07001356 /** Returns whether x and y originated within the buffered viewport */
1357 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1358 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1359 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1360 return mTmpRect.contains(x, y);
1361 }
1362
Winson Chung321e9ee2010-08-09 13:37:56 -07001363 @Override
1364 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001365 if (DISABLE_TOUCH_INTERACTION) {
1366 return false;
1367 }
1368
Winson Chung321e9ee2010-08-09 13:37:56 -07001369 /*
1370 * This method JUST determines whether we want to intercept the motion.
1371 * If we return true, onTouchEvent will be called and we do the actual
1372 * scrolling there.
1373 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001374 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001375
Winson Chung45e1d6e2010-11-09 17:19:49 -08001376 // Skip touch handling if there are no pages to swipe
1377 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1378
Winson Chung321e9ee2010-08-09 13:37:56 -07001379 /*
1380 * Shortcut the most recurring case: the user is in the dragging
1381 * state and he is moving his finger. We want to intercept this
1382 * motion.
1383 */
1384 final int action = ev.getAction();
1385 if ((action == MotionEvent.ACTION_MOVE) &&
1386 (mTouchState == TOUCH_STATE_SCROLLING)) {
1387 return true;
1388 }
1389
Winson Chung321e9ee2010-08-09 13:37:56 -07001390 switch (action & MotionEvent.ACTION_MASK) {
1391 case MotionEvent.ACTION_MOVE: {
1392 /*
1393 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1394 * whether the user has moved far enough from his original down touch.
1395 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001396 if (mActivePointerId != INVALID_POINTER) {
1397 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001398 }
1399 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1400 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1401 // i.e. fall through to the next case (don't break)
1402 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1403 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001404 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001405 }
1406
1407 case MotionEvent.ACTION_DOWN: {
1408 final float x = ev.getX();
1409 final float y = ev.getY();
1410 // Remember location of down touch
1411 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001412 mDownMotionY = y;
1413 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001414 mLastMotionX = x;
1415 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001416 float[] p = mapPointFromViewToParent(this, x, y);
1417 mParentDownMotionX = p[0];
1418 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001419 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001420 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001421 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001422
Winson Chung321e9ee2010-08-09 13:37:56 -07001423 /*
1424 * If being flinged and user touches the screen, initiate drag;
1425 * otherwise don't. mScroller.isFinished should be false when
1426 * being flinged.
1427 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001428 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Adam Cohena7652152013-11-18 20:06:55 +00001429 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop / 3);
Adam Cohen2da0a052013-11-08 06:28:17 -08001430
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001431 if (finishedScrolling) {
1432 mTouchState = TOUCH_STATE_REST;
Adam Cohen59b5c792013-12-04 16:09:07 -08001433 if (!mScroller.isFinished() && !mFreeScroll) {
Adam Cohena7652152013-11-18 20:06:55 +00001434 setCurrentPage(getNextPage());
1435 pageEndMoving();
Adam Cohen2da0a052013-11-08 06:28:17 -08001436 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001437 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001438 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1439 mTouchState = TOUCH_STATE_SCROLLING;
1440 } else {
1441 mTouchState = TOUCH_STATE_REST;
1442 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001443 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001444
Winson Chung86f77532010-08-24 11:08:22 -07001445 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001446 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001447 if (!DISABLE_TOUCH_SIDE_PAGES) {
1448 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1449 if (getChildCount() > 0) {
1450 if (hitsPreviousPage(x, y)) {
1451 mTouchState = TOUCH_STATE_PREV_PAGE;
1452 } else if (hitsNextPage(x, y)) {
1453 mTouchState = TOUCH_STATE_NEXT_PAGE;
1454 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001455 }
1456 }
1457 }
1458 break;
1459 }
1460
Winson Chung321e9ee2010-08-09 13:37:56 -07001461 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001462 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001463 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001464 break;
1465
1466 case MotionEvent.ACTION_POINTER_UP:
1467 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001468 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001469 break;
1470 }
1471
1472 /*
1473 * The only time we want to intercept motion events is if we are in the
1474 * drag mode.
1475 */
1476 return mTouchState != TOUCH_STATE_REST;
1477 }
1478
Adam Cohenf8d28232011-02-01 21:47:00 -08001479 protected void determineScrollingStart(MotionEvent ev) {
1480 determineScrollingStart(ev, 1.0f);
1481 }
1482
Winson Chung321e9ee2010-08-09 13:37:56 -07001483 /*
1484 * Determines if we should change the touch state to start scrolling after the
1485 * user moves their touch point too far.
1486 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001487 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001488 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001489 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001490 if (pointerIndex == -1) return;
1491
1492 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001493 final float x = ev.getX(pointerIndex);
1494 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001495 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1496
Winson Chung321e9ee2010-08-09 13:37:56 -07001497 final int xDiff = (int) Math.abs(x - mLastMotionX);
1498 final int yDiff = (int) Math.abs(y - mLastMotionY);
1499
Adam Cohenf8d28232011-02-01 21:47:00 -08001500 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001501 boolean xPaged = xDiff > mPagingTouchSlop;
1502 boolean xMoved = xDiff > touchSlop;
1503 boolean yMoved = yDiff > touchSlop;
1504
Adam Cohenf8d28232011-02-01 21:47:00 -08001505 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001506 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001507 // Scroll if the user moved far enough along the X axis
1508 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001509 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001510 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001511 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001512 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001513 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1514 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001515 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001516 }
1517 }
1518
Adam Cohen7d30a372013-07-01 17:03:59 -07001519 protected float getMaxScrollProgress() {
1520 return 1.0f;
1521 }
1522
Adam Cohenf8d28232011-02-01 21:47:00 -08001523 protected void cancelCurrentPageLongPress() {
1524 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001525 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001526 // Try canceling the long press. It could also have been scheduled
1527 // by a distant descendant, so use the mAllowLongPress flag to block
1528 // everything
1529 final View currentPage = getPageAt(mCurrentPage);
1530 if (currentPage != null) {
1531 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001532 }
1533 }
1534 }
1535
Adam Cohen7d30a372013-07-01 17:03:59 -07001536 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1537 final int halfScreenSize = getViewportWidth() / 2;
1538
1539 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1540 screenCenter = Math.max(halfScreenSize, screenCenter);
1541
1542 return getScrollProgress(screenCenter, v, page);
1543 }
1544
Adam Cohenb5ba0972011-09-07 18:02:31 -07001545 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001546 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001547
Adam Cohenedb40762013-07-18 16:45:45 -07001548 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohen3b185e22013-10-29 14:45:58 -07001549 int count = getChildCount();
1550
1551 final int totalDistance;
1552
1553 int adjacentPage = page + 1;
1554 if ((delta < 0 && !isLayoutRtl()) || (delta > 0 && isLayoutRtl())) {
1555 adjacentPage = page - 1;
1556 }
1557
1558 if (adjacentPage < 0 || adjacentPage > count - 1) {
1559 totalDistance = v.getMeasuredWidth() + mPageSpacing;
1560 } else {
1561 totalDistance = Math.abs(getScrollForPage(adjacentPage) - getScrollForPage(page));
1562 }
Adam Cohenb5ba0972011-09-07 18:02:31 -07001563
1564 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001565 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1566 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001567 return scrollProgress;
1568 }
1569
Adam Cohenedb40762013-07-18 16:45:45 -07001570 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001571 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001572 return 0;
1573 } else {
1574 return mPageScrolls[index];
1575 }
1576 }
1577
Adam Cohen564a2e72013-10-09 14:47:32 -07001578 // While layout transitions are occurring, a child's position may stray from its baseline
1579 // position. This method returns the magnitude of this stray at any given time.
1580 public int getLayoutTransitionOffsetForPage(int index) {
1581 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1582 return 0;
1583 } else {
1584 View child = getChildAt(index);
Adam Cohen3b185e22013-10-29 14:45:58 -07001585
1586 int scrollOffset = 0;
1587 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1588 if (!lp.isFullScreenPage) {
1589 scrollOffset = isLayoutRtl() ? getPaddingRight() : getPaddingLeft();
1590 }
1591
Adam Cohen564a2e72013-10-09 14:47:32 -07001592 int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
1593 return (int) (child.getX() - baselineX);
1594 }
1595 }
1596
Adam Cohene0f66b52010-11-23 15:06:07 -08001597 // This curve determines how the effect of scrolling over the limits of the page dimishes
1598 // as the user pulls further and further from the bounds
1599 private float overScrollInfluenceCurve(float f) {
1600 f -= 1.0f;
1601 return f * f * f + 1.0f;
1602 }
1603
Adam Cohenb5ba0972011-09-07 18:02:31 -07001604 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001605 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001606
1607 // We want to reach the max over scroll effect when the user has
1608 // over scrolled half the size of the screen
1609 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1610
1611 if (f == 0) return;
1612
1613 // Clamp this factor, f, to -1 < f < 1
1614 if (Math.abs(f) >= 1) {
1615 f /= Math.abs(f);
1616 }
1617
1618 int overScrollAmount = (int) Math.round(f * screenSize);
1619 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001620 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001621 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001622 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001623 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001624 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001625 }
1626 invalidate();
1627 }
1628
1629 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001630 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001631
1632 float f = (amount / screenSize);
1633
1634 if (f == 0) return;
1635 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1636
Adam Cohen7bfc9792011-01-28 13:52:37 -08001637 // Clamp this factor, f, to -1 < f < 1
1638 if (Math.abs(f) >= 1) {
1639 f /= Math.abs(f);
1640 }
1641
Adam Cohene0f66b52010-11-23 15:06:07 -08001642 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001643 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001644 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001645 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001646 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001647 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001648 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001649 }
1650 invalidate();
1651 }
1652
Adam Cohenb5ba0972011-09-07 18:02:31 -07001653 protected void overScroll(float amount) {
1654 dampedOverScroll(amount);
1655 }
1656
Michael Jurkac5b262c2011-01-12 20:24:50 -08001657 protected float maxOverScroll() {
1658 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001659 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001660 float f = 1.0f;
1661 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1662 return OVERSCROLL_DAMP_FACTOR * f;
1663 }
1664
Adam Cohenf358a4b2013-07-23 16:47:31 -07001665 protected void enableFreeScroll() {
Adam Cohenf9618852013-11-08 06:45:03 -08001666 setEnableFreeScroll(true);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001667 }
1668
Adam Cohenf9618852013-11-08 06:45:03 -08001669 protected void disableFreeScroll() {
1670 setEnableFreeScroll(false);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001671 }
1672
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001673 void updateFreescrollBounds() {
Adam Cohen6f127a62014-06-12 14:54:41 -07001674 getFreeScrollPageRange(mTempVisiblePagesRange);
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001675 if (isLayoutRtl()) {
1676 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1677 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1678 } else {
1679 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1680 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1681 }
1682 }
1683
Adam Cohenf9618852013-11-08 06:45:03 -08001684 private void setEnableFreeScroll(boolean freeScroll) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001685 mFreeScroll = freeScroll;
1686
Adam Cohenf9618852013-11-08 06:45:03 -08001687 if (mFreeScroll) {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001688 updateFreescrollBounds();
Adam Cohen6f127a62014-06-12 14:54:41 -07001689 getFreeScrollPageRange(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001690 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1691 setCurrentPage(mTempVisiblePagesRange[0]);
1692 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1693 setCurrentPage(mTempVisiblePagesRange[1]);
1694 }
1695 }
1696
1697 setEnableOverscroll(!freeScroll);
1698 }
1699
1700 private void setEnableOverscroll(boolean enable) {
1701 mAllowOverScroll = enable;
1702 }
1703
1704 int getNearestHoverOverPageIndex() {
1705 if (mDragView != null) {
1706 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1707 + mDragView.getTranslationX());
Adam Cohen6f127a62014-06-12 14:54:41 -07001708 getFreeScrollPageRange(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001709 int minDistance = Integer.MAX_VALUE;
1710 int minIndex = indexOfChild(mDragView);
1711 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1712 View page = getPageAt(i);
1713 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1714 int d = Math.abs(dragX - pageX);
1715 if (d < minDistance) {
1716 minIndex = i;
1717 minDistance = d;
1718 }
1719 }
1720 return minIndex;
1721 }
1722 return -1;
1723 }
1724
Winson Chung321e9ee2010-08-09 13:37:56 -07001725 @Override
1726 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001727 if (DISABLE_TOUCH_INTERACTION) {
1728 return false;
1729 }
1730
Adam Cohen1697b792013-09-17 19:08:21 -07001731 super.onTouchEvent(ev);
1732
Winson Chung45e1d6e2010-11-09 17:19:49 -08001733 // Skip touch handling if there are no pages to swipe
1734 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1735
Michael Jurkab8f06722010-10-10 15:58:46 -07001736 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001737
1738 final int action = ev.getAction();
1739
1740 switch (action & MotionEvent.ACTION_MASK) {
1741 case MotionEvent.ACTION_DOWN:
1742 /*
1743 * If being flinged and user touches, stop the fling. isFinished
1744 * will be false if being flinged.
1745 */
1746 if (!mScroller.isFinished()) {
Adam Cohen8bdbaab2013-10-29 15:25:02 -07001747 abortScrollerAnimation(false);
Winson Chung321e9ee2010-08-09 13:37:56 -07001748 }
1749
1750 // Remember where the motion event started
1751 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001752 mDownMotionY = mLastMotionY = ev.getY();
1753 mDownScrollX = getScrollX();
1754 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1755 mParentDownMotionX = p[0];
1756 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001757 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001758 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001759 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001760
Michael Jurka0142d492010-08-25 17:46:15 -07001761 if (mTouchState == TOUCH_STATE_SCROLLING) {
1762 pageBeginMoving();
1763 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001764 break;
1765
1766 case MotionEvent.ACTION_MOVE:
1767 if (mTouchState == TOUCH_STATE_SCROLLING) {
1768 // Scroll to follow the motion event
1769 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001770
1771 if (pointerIndex == -1) return true;
1772
Winson Chung321e9ee2010-08-09 13:37:56 -07001773 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001774 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001775
Adam Cohenaefd4e12011-02-14 16:39:38 -08001776 mTotalMotionX += Math.abs(deltaX);
1777
Winson Chungc0844aa2011-02-02 15:25:58 -08001778 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1779 // keep the remainder because we are actually testing if we've moved from the last
1780 // scrolled position (which is discrete).
1781 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001782 mTouchX += deltaX;
1783 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1784 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001785 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001786 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001787 } else {
1788 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001789 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001790 mLastMotionX = x;
1791 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001792 } else {
1793 awakenScrollBars();
1794 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001795 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1796 // Update the last motion position
1797 mLastMotionX = ev.getX();
1798 mLastMotionY = ev.getY();
1799
1800 // Update the parent down so that our zoom animations take this new movement into
1801 // account
1802 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1803 mParentDownMotionX = pt[0];
1804 mParentDownMotionY = pt[1];
1805 updateDragViewTranslationDuringDrag();
1806
1807 // Find the closest page to the touch point
1808 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001809
1810 // Change the drag view if we are hovering over the drop target
1811 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1812 (int) mParentDownMotionX, (int) mParentDownMotionY);
1813 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1814
Adam Cohen7d30a372013-07-01 17:03:59 -07001815 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1816 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1817 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1818 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1819
Adam Cohenf358a4b2013-07-23 16:47:31 -07001820 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1821 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1822 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001823 mTempVisiblePagesRange[0] = 0;
1824 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohen6f127a62014-06-12 14:54:41 -07001825 getFreeScrollPageRange(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001826 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1827 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1828 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1829 mSidePageHoverIndex = pageUnderPointIndex;
1830 mSidePageHoverRunnable = new Runnable() {
1831 @Override
1832 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001833 // Setup the scroll to the correct page before we swap the views
1834 snapToPage(pageUnderPointIndex);
1835
1836 // For each of the pages between the paged view and the drag view,
1837 // animate them from the previous position to the new position in
1838 // the layout (as a result of the drag view moving in the layout)
1839 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1840 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1841 dragViewIndex + 1 : pageUnderPointIndex;
1842 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1843 dragViewIndex - 1 : pageUnderPointIndex;
1844 for (int i = lowerIndex; i <= upperIndex; ++i) {
1845 View v = getChildAt(i);
1846 // dragViewIndex < pageUnderPointIndex, so after we remove the
1847 // drag view all subsequent views to pageUnderPointIndex will
1848 // shift down.
1849 int oldX = getViewportOffsetX() + getChildOffset(i);
1850 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1851
1852 // Animate the view translation from its old position to its new
1853 // position
1854 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1855 if (anim != null) {
1856 anim.cancel();
1857 }
1858
1859 v.setTranslationX(oldX - newX);
1860 anim = new AnimatorSet();
1861 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1862 anim.playTogether(
1863 ObjectAnimator.ofFloat(v, "translationX", 0f));
1864 anim.start();
1865 v.setTag(anim);
1866 }
1867
1868 removeView(mDragView);
1869 onRemoveView(mDragView, false);
1870 addView(mDragView, pageUnderPointIndex);
1871 onAddView(mDragView, pageUnderPointIndex);
1872 mSidePageHoverIndex = -1;
Winson Chung876a6192013-11-06 14:49:50 -08001873 if (mPageIndicator != null) {
1874 mPageIndicator.setActiveMarker(getNextPage());
1875 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001876 }
1877 };
1878 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1879 }
1880 } else {
1881 removeCallbacks(mSidePageHoverRunnable);
1882 mSidePageHoverIndex = -1;
1883 }
Adam Cohen564976a2010-10-13 18:52:07 -07001884 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001885 determineScrollingStart(ev);
1886 }
1887 break;
1888
1889 case MotionEvent.ACTION_UP:
1890 if (mTouchState == TOUCH_STATE_SCROLLING) {
1891 final int activePointerId = mActivePointerId;
1892 final int pointerIndex = ev.findPointerIndex(activePointerId);
1893 final float x = ev.getX(pointerIndex);
1894 final VelocityTracker velocityTracker = mVelocityTracker;
1895 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1896 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001897 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001898 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001899 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1900 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001901
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001902 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1903
Adam Cohen00481b32011-11-18 12:03:48 -08001904 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001905 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001906
Adam Cohenf358a4b2013-07-23 16:47:31 -07001907 if (!mFreeScroll) {
1908 // In the case that the page is moved far to one direction and then is flung
1909 // in the opposite direction, we use a threshold to determine whether we should
1910 // just return to the starting page, or if we should skip one further.
1911 boolean returnToOriginalPage = false;
1912 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1913 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1914 returnToOriginalPage = true;
1915 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001916
Adam Cohenf358a4b2013-07-23 16:47:31 -07001917 int finalPage;
1918 // We give flings precedence over large moves, which is why we short-circuit our
1919 // test for a large move if a fling has been registered. That is, a large
1920 // move to the left and fling to the right will register as a fling to the right.
1921 final boolean isRtl = isLayoutRtl();
1922 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1923 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1924 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1925 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1926 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1927 snapToPageWithVelocity(finalPage, velocityX);
1928 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1929 (isFling && isVelocityXLeft)) &&
1930 mCurrentPage < getChildCount() - 1) {
1931 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1932 snapToPageWithVelocity(finalPage, velocityX);
1933 } else {
1934 snapToDestination();
Adam Cohenf358a4b2013-07-23 16:47:31 -07001935 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001936 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001937 if (!mScroller.isFinished()) {
Adam Cohen8bdbaab2013-10-29 15:25:02 -07001938 abortScrollerAnimation(true);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001939 }
1940
1941 float scaleX = getScaleX();
1942 int vX = (int) (-velocityX * scaleX);
1943 int initialScrollX = (int) (getScrollX() * scaleX);
1944
Adam Cohenf9618852013-11-08 06:45:03 -08001945 mScroller.setInterpolator(mDefaultInterpolator);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001946 mScroller.fling(initialScrollX,
1947 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1948 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001949 }
Adam Cohencae7f572013-11-04 14:42:52 -08001950 } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1951 // at this point we have not moved beyond the touch slop
1952 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1953 // we can just page
1954 int nextPage = Math.max(0, mCurrentPage - 1);
1955 if (nextPage != mCurrentPage) {
1956 snapToPage(nextPage);
1957 } else {
1958 snapToDestination();
1959 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001960 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001961 // at this point we have not moved beyond the touch slop
1962 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1963 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001964 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1965 if (nextPage != mCurrentPage) {
1966 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001967 } else {
1968 snapToDestination();
1969 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001970 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1971 // Update the last motion position
1972 mLastMotionX = ev.getX();
1973 mLastMotionY = ev.getY();
1974
1975 // Update the parent down so that our zoom animations take this new movement into
1976 // account
1977 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1978 mParentDownMotionX = pt[0];
1979 mParentDownMotionY = pt[1];
1980 updateDragViewTranslationDuringDrag();
1981 boolean handledFling = false;
1982 if (!DISABLE_FLING_TO_DELETE) {
1983 // Check the velocity and see if we are flinging-to-delete
1984 PointF flingToDeleteVector = isFlingingToDelete();
1985 if (flingToDeleteVector != null) {
1986 onFlingToDelete(flingToDeleteVector);
1987 handledFling = true;
1988 }
1989 }
1990 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1991 (int) mParentDownMotionY)) {
1992 onDropToDelete();
1993 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001994 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001995 if (!mCancelTap) {
1996 onUnhandledTap(ev);
1997 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001998 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001999
2000 // Remove the callback to wait for the side page hover timeout
2001 removeCallbacks(mSidePageHoverRunnable);
2002 // End any intermediate reordering states
2003 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07002004 break;
2005
2006 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07002007 if (mTouchState == TOUCH_STATE_SCROLLING) {
2008 snapToDestination();
2009 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002010 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07002011 break;
2012
2013 case MotionEvent.ACTION_POINTER_UP:
2014 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07002015 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07002016 break;
2017 }
2018
2019 return true;
2020 }
2021
Adam Cohen7d30a372013-07-01 17:03:59 -07002022 public void onFlingToDelete(View v) {}
2023 public void onRemoveView(View v, boolean deletePermanently) {}
2024 public void onRemoveViewAnimationCompleted() {}
2025 public void onAddView(View v, int index) {}
2026
2027 private void resetTouchState() {
2028 releaseVelocityTracker();
2029 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07002030 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002031 mTouchState = TOUCH_STATE_REST;
2032 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07002033 }
2034
Adam Cohen1697b792013-09-17 19:08:21 -07002035 protected void onUnhandledTap(MotionEvent ev) {
2036 ((Launcher) getContext()).onClick(this);
2037 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002038
Winson Chung185d7162011-02-28 13:47:29 -08002039 @Override
2040 public boolean onGenericMotionEvent(MotionEvent event) {
2041 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
2042 switch (event.getAction()) {
2043 case MotionEvent.ACTION_SCROLL: {
2044 // Handle mouse (or ext. device) by shifting the page depending on the scroll
2045 final float vscroll;
2046 final float hscroll;
2047 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
2048 vscroll = 0;
2049 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
2050 } else {
2051 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
2052 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
2053 }
2054 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07002055 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
2056 : (hscroll > 0 || vscroll > 0);
2057 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08002058 scrollRight();
2059 } else {
2060 scrollLeft();
2061 }
2062 return true;
2063 }
2064 }
2065 }
2066 }
2067 return super.onGenericMotionEvent(event);
2068 }
2069
Michael Jurkab8f06722010-10-10 15:58:46 -07002070 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
2071 if (mVelocityTracker == null) {
2072 mVelocityTracker = VelocityTracker.obtain();
2073 }
2074 mVelocityTracker.addMovement(ev);
2075 }
2076
2077 private void releaseVelocityTracker() {
2078 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002079 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07002080 mVelocityTracker.recycle();
2081 mVelocityTracker = null;
2082 }
2083 }
2084
Winson Chung321e9ee2010-08-09 13:37:56 -07002085 private void onSecondaryPointerUp(MotionEvent ev) {
2086 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
2087 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
2088 final int pointerId = ev.getPointerId(pointerIndex);
2089 if (pointerId == mActivePointerId) {
2090 // This was our active pointer going up. Choose a new
2091 // active pointer and adjust accordingly.
2092 // TODO: Make this decision more intelligent.
2093 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2094 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
2095 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08002096 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07002097 mActivePointerId = ev.getPointerId(newPointerIndex);
2098 if (mVelocityTracker != null) {
2099 mVelocityTracker.clear();
2100 }
2101 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08002102 }
2103
Winson Chung321e9ee2010-08-09 13:37:56 -07002104 @Override
2105 public void requestChildFocus(View child, View focused) {
2106 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002107 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002108 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002109 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002110 }
2111 }
2112
Winson Chung1908d072011-02-24 18:09:44 -08002113 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002114 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002115 }
2116
Adam Cohen7d30a372013-07-01 17:03:59 -07002117 int getPageNearestToPoint(float x) {
2118 int index = 0;
2119 for (int i = 0; i < getChildCount(); ++i) {
2120 if (x < getChildAt(i).getRight() - getScrollX()) {
2121 return index;
2122 } else {
2123 index++;
2124 }
2125 }
2126 return Math.min(index, getChildCount() - 1);
2127 }
2128
Adam Cohend19d3ca2010-09-15 14:43:42 -07002129 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002130 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002131 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002132 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002133 final int childCount = getChildCount();
2134 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002135 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002136 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002137 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002138 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002139 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2140 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2141 minDistanceFromScreenCenter = distanceFromScreenCenter;
2142 minDistanceFromScreenCenterIndex = i;
2143 }
2144 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002145 return minDistanceFromScreenCenterIndex;
2146 }
2147
2148 protected void snapToDestination() {
2149 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002150 }
2151
Adam Cohene0f66b52010-11-23 15:06:07 -08002152 private static class ScrollInterpolator implements Interpolator {
2153 public ScrollInterpolator() {
2154 }
2155
2156 public float getInterpolation(float t) {
2157 t -= 1.0f;
2158 return t*t*t*t*t + 1;
2159 }
2160 }
2161
2162 // We want the duration of the page snap animation to be influenced by the distance that
2163 // the screen has to travel, however, we don't want this duration to be effected in a
2164 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2165 // of travel has on the overall snap duration.
2166 float distanceInfluenceForSnapDuration(float f) {
2167 f -= 0.5f; // center the values about 0.
2168 f *= 0.3f * Math.PI / 2.0f;
2169 return (float) Math.sin(f);
2170 }
2171
Michael Jurka0142d492010-08-25 17:46:15 -07002172 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohen6f127a62014-06-12 14:54:41 -07002173 whichPage = validateNewPage(whichPage);
Adam Cohen7d30a372013-07-01 17:03:59 -07002174 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002175
Adam Cohenedb40762013-07-18 16:45:45 -07002176 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002177 int delta = newX - mUnboundedScrollX;
2178 int duration = 0;
2179
Adam Cohen265b9a62011-12-07 14:37:18 -08002180 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002181 // If the velocity is low enough, then treat this more as an automatic page advance
2182 // as opposed to an apparent physical response to flinging
2183 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2184 return;
2185 }
2186
2187 // Here we compute a "distance" that will be used in the computation of the overall
2188 // snap duration. This is a function of the actual distance that needs to be traveled;
2189 // we keep this value close to half screen size in order to reduce the variance in snap
2190 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002191 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002192 float distance = halfScreenSize + halfScreenSize *
2193 distanceInfluenceForSnapDuration(distanceRatio);
2194
2195 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002196 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002197
2198 // we want the page's snap velocity to approximately match the velocity at which the
2199 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002200 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2201 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002202
2203 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002204 }
2205
2206 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002207 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002208 }
2209
Adam Cohen7d30a372013-07-01 17:03:59 -07002210 protected void snapToPageImmediately(int whichPage) {
Adam Cohenf9618852013-11-08 06:45:03 -08002211 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true, null);
Adam Cohen7d30a372013-07-01 17:03:59 -07002212 }
2213
Michael Jurka0142d492010-08-25 17:46:15 -07002214 protected void snapToPage(int whichPage, int duration) {
Adam Cohenf9618852013-11-08 06:45:03 -08002215 snapToPage(whichPage, duration, false, null);
Adam Cohen7d30a372013-07-01 17:03:59 -07002216 }
2217
Adam Cohenf9618852013-11-08 06:45:03 -08002218 protected void snapToPage(int whichPage, int duration, TimeInterpolator interpolator) {
2219 snapToPage(whichPage, duration, false, interpolator);
2220 }
2221
2222 protected void snapToPage(int whichPage, int duration, boolean immediate,
2223 TimeInterpolator interpolator) {
Adam Cohen6f127a62014-06-12 14:54:41 -07002224 whichPage = validateNewPage(whichPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002225
Adam Cohenedb40762013-07-18 16:45:45 -07002226 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002227 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002228 final int delta = newX - sX;
Adam Cohenf9618852013-11-08 06:45:03 -08002229 snapToPage(whichPage, delta, duration, immediate, interpolator);
Michael Jurka0142d492010-08-25 17:46:15 -07002230 }
2231
2232 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohenf9618852013-11-08 06:45:03 -08002233 snapToPage(whichPage, delta, duration, false, null);
Adam Cohen7d30a372013-07-01 17:03:59 -07002234 }
Michael Jurka0142d492010-08-25 17:46:15 -07002235
Adam Cohenf9618852013-11-08 06:45:03 -08002236 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate,
2237 TimeInterpolator interpolator) {
Adam Cohen6f127a62014-06-12 14:54:41 -07002238 whichPage = validateNewPage(whichPage);
2239
Adam Cohen7d30a372013-07-01 17:03:59 -07002240 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002241 View focusedChild = getFocusedChild();
2242 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002243 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002244 focusedChild.clearFocus();
2245 }
2246
Adam Cohen53805212013-10-01 10:39:23 -07002247 sendScrollAccessibilityEvent();
2248
Michael Jurka0142d492010-08-25 17:46:15 -07002249 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002250 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002251 if (immediate) {
2252 duration = 0;
2253 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002254 duration = Math.abs(delta);
2255 }
2256
Adam Cohenf358a4b2013-07-23 16:47:31 -07002257 if (!mScroller.isFinished()) {
Adam Cohenf9618852013-11-08 06:45:03 -08002258 abortScrollerAnimation(false);
Adam Cohenf358a4b2013-07-23 16:47:31 -07002259 }
Adam Cohenf9618852013-11-08 06:45:03 -08002260
2261 if (interpolator != null) {
2262 mScroller.setInterpolator(interpolator);
2263 } else {
2264 mScroller.setInterpolator(mDefaultInterpolator);
2265 }
2266
Adam Cohen68d73932010-11-15 10:50:58 -08002267 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002268
Adam Cohen674531f2013-12-13 15:07:14 -08002269 updatePageIndicator();
Adam Cohen7d30a372013-07-01 17:03:59 -07002270
2271 // Trigger a compute() to finish switching pages if necessary
2272 if (immediate) {
2273 computeScroll();
2274 }
2275
Winson Chung9c0565f2013-07-19 13:49:06 -07002276 // Defer loading associated pages until the scroll settles
2277 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2278
Adam Cohen7d30a372013-07-01 17:03:59 -07002279 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002280 invalidate();
2281 }
2282
Winson Chung321e9ee2010-08-09 13:37:56 -07002283 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002284 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002285 }
2286
2287 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002288 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002289 }
2290
Winson Chung86f77532010-08-24 11:08:22 -07002291 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002292 int result = -1;
2293 if (v != null) {
2294 ViewParent vp = v.getParent();
2295 int count = getChildCount();
2296 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002297 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002298 return i;
2299 }
2300 }
2301 }
2302 return result;
2303 }
2304
2305 /**
2306 * @return True is long presses are still allowed for the current touch
2307 */
2308 public boolean allowLongPress() {
2309 return mAllowLongPress;
2310 }
2311
Adam Cohendbdff6b2013-09-18 19:09:15 -07002312 @Override
2313 public boolean performLongClick() {
2314 mCancelTap = true;
2315 return super.performLongClick();
2316 }
2317
Michael Jurka0142d492010-08-25 17:46:15 -07002318 /**
2319 * Set true to allow long-press events to be triggered, usually checked by
2320 * {@link Launcher} to accept or block dpad-initiated long-presses.
2321 */
2322 public void setAllowLongPress(boolean allowLongPress) {
2323 mAllowLongPress = allowLongPress;
2324 }
2325
Winson Chung321e9ee2010-08-09 13:37:56 -07002326 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002327 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002328
2329 SavedState(Parcelable superState) {
2330 super(superState);
2331 }
2332
2333 private SavedState(Parcel in) {
2334 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002335 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002336 }
2337
2338 @Override
2339 public void writeToParcel(Parcel out, int flags) {
2340 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002341 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002342 }
2343
2344 public static final Parcelable.Creator<SavedState> CREATOR =
2345 new Parcelable.Creator<SavedState>() {
2346 public SavedState createFromParcel(Parcel in) {
2347 return new SavedState(in);
2348 }
2349
2350 public SavedState[] newArray(int size) {
2351 return new SavedState[size];
2352 }
2353 };
2354 }
2355
Winson Chungf314b0e2011-08-16 11:54:27 -07002356 protected void loadAssociatedPages(int page) {
2357 loadAssociatedPages(page, false);
2358 }
2359 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002360 if (mContentIsRefreshable) {
2361 final int count = getChildCount();
2362 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002363 int lowerPageBound = getAssociatedLowerPageBound(page);
2364 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002365 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2366 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002367 // First, clear any pages that should no longer be loaded
2368 for (int i = 0; i < count; ++i) {
2369 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002370 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002371 if (layout.getPageChildCount() > 0) {
2372 layout.removeAllViewsOnPage();
2373 }
2374 mDirtyPageContent.set(i, true);
2375 }
2376 }
2377 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002378 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002379 if ((i != page) && immediateAndOnly) {
2380 continue;
2381 }
Michael Jurka0142d492010-08-25 17:46:15 -07002382 if (lowerPageBound <= i && i <= upperPageBound) {
2383 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002384 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002385 mDirtyPageContent.set(i, false);
2386 }
Winson Chung86f77532010-08-24 11:08:22 -07002387 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002388 }
2389 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002390 }
2391 }
2392
Winson Chunge3193b92010-09-10 11:44:42 -07002393 protected int getAssociatedLowerPageBound(int page) {
2394 return Math.max(0, page - 1);
2395 }
2396 protected int getAssociatedUpperPageBound(int page) {
2397 final int count = getChildCount();
2398 return Math.min(page + 1, count - 1);
2399 }
2400
Winson Chung86f77532010-08-24 11:08:22 -07002401 /**
2402 * This method is called ONLY to synchronize the number of pages that the paged view has.
2403 * To actually fill the pages with information, implement syncPageItems() below. It is
2404 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2405 * and therefore, individual page items do not need to be updated in this method.
2406 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002407 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002408
2409 /**
2410 * This method is called to synchronize the items that are on a particular page. If views on
2411 * the page can be reused, then they should be updated within this method.
2412 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002413 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002414
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002415 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002416 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002417 }
2418 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002419 invalidatePageData(currentPage, false);
2420 }
2421 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002422 if (!mIsDataReady) {
2423 return;
2424 }
2425
Michael Jurka0142d492010-08-25 17:46:15 -07002426 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002427 // Force all scrolling-related behavior to end
Adam Cohen4fe4c932013-10-28 16:02:34 -07002428 forceFinishScroller();
Adam Cohen0cd3b642011-10-14 14:58:00 -07002429
Michael Jurka0142d492010-08-25 17:46:15 -07002430 // Update all the pages
2431 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002432
Winson Chung5a808352011-06-27 19:08:49 -07002433 // We must force a measure after we've loaded the pages to update the content width and
2434 // to determine the full scroll width
2435 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2436 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2437
2438 // Set a new page as the current page if necessary
2439 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002440 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002441 }
2442
Michael Jurka0142d492010-08-25 17:46:15 -07002443 // Mark each of the pages as dirty
2444 final int count = getChildCount();
2445 mDirtyPageContent.clear();
2446 for (int i = 0; i < count; ++i) {
2447 mDirtyPageContent.add(true);
2448 }
2449
2450 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002451 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002452 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002453 }
Adam Cohen06559042013-09-29 18:30:56 -07002454 if (isPageMoving()) {
2455 // If the page is moving, then snap it to the final position to ensure we don't get
2456 // stuck between pages
2457 snapToDestination();
2458 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002459 }
Winson Chung007c6982011-06-14 13:27:53 -07002460
Adam Cohen7d30a372013-07-01 17:03:59 -07002461 // Animate the drag view back to the original position
2462 void animateDragViewToOriginalPosition() {
2463 if (mDragView != null) {
2464 AnimatorSet anim = new AnimatorSet();
2465 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2466 anim.playTogether(
2467 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002468 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2469 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2470 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002471 anim.addListener(new AnimatorListenerAdapter() {
2472 @Override
2473 public void onAnimationEnd(Animator animation) {
2474 onPostReorderingAnimationCompleted();
2475 }
2476 });
2477 anim.start();
2478 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002479 }
2480
Adam Cohen7d30a372013-07-01 17:03:59 -07002481 protected void onStartReordering() {
2482 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2483 mTouchState = TOUCH_STATE_REORDERING;
2484 mIsReordering = true;
2485
Adam Cohen7d30a372013-07-01 17:03:59 -07002486 // We must invalidate to trigger a redraw to update the layers such that the drag view
2487 // is always drawn on top
2488 invalidate();
2489 }
2490
2491 private void onPostReorderingAnimationCompleted() {
2492 // Trigger the callback when reordering has settled
2493 --mPostReorderingPreZoomInRemainingAnimationCount;
2494 if (mPostReorderingPreZoomInRunnable != null &&
2495 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2496 mPostReorderingPreZoomInRunnable.run();
2497 mPostReorderingPreZoomInRunnable = null;
2498 }
2499 }
2500
2501 protected void onEndReordering() {
2502 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002503 }
2504
Adam Cohenf358a4b2013-07-23 16:47:31 -07002505 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002506 int dragViewIndex = indexOfChild(v);
2507
Adam Cohen327acfe2014-06-06 11:52:52 -07002508 if (mTouchState != TOUCH_STATE_REST || dragViewIndex == -1) return false;
Adam Cohen93c97562013-09-26 13:48:01 -07002509
Adam Cohen7d30a372013-07-01 17:03:59 -07002510 mTempVisiblePagesRange[0] = 0;
2511 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohen6f127a62014-06-12 14:54:41 -07002512 getFreeScrollPageRange(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002513 mReorderingStarted = true;
2514
2515 // Check if we are within the reordering range
2516 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002517 dragViewIndex <= mTempVisiblePagesRange[1]) {
2518 // Find the drag view under the pointer
2519 mDragView = getChildAt(dragViewIndex);
2520 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2521 mDragViewBaselineLeft = mDragView.getLeft();
Adam Cohenf9618852013-11-08 06:45:03 -08002522 snapToPage(getPageNearestToCenterOfScreen());
2523 disableFreeScroll();
Adam Cohenf358a4b2013-07-23 16:47:31 -07002524 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002525 return true;
2526 }
2527 return false;
2528 }
2529
2530 boolean isReordering(boolean testTouchState) {
2531 boolean state = mIsReordering;
2532 if (testTouchState) {
2533 state &= (mTouchState == TOUCH_STATE_REORDERING);
2534 }
2535 return state;
2536 }
2537 void endReordering() {
2538 // For simplicity, we call endReordering sometimes even if reordering was never started.
2539 // In that case, we don't want to do anything.
2540 if (!mReorderingStarted) return;
2541 mReorderingStarted = false;
2542
2543 // If we haven't flung-to-delete the current child, then we just animate the drag view
2544 // back into position
2545 final Runnable onCompleteRunnable = new Runnable() {
2546 @Override
2547 public void run() {
2548 onEndReordering();
2549 }
2550 };
2551 if (!mDeferringForDelete) {
2552 mPostReorderingPreZoomInRunnable = new Runnable() {
2553 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002554 onCompleteRunnable.run();
2555 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002556 };
2557 };
2558
2559 mPostReorderingPreZoomInRemainingAnimationCount =
2560 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2561 // Snap to the current page
2562 snapToPage(indexOfChild(mDragView), 0);
2563 // Animate the drag view back to the front position
2564 animateDragViewToOriginalPosition();
2565 } else {
2566 // Handled in post-delete-animation-callbacks
2567 }
2568 }
2569
Adam Cohen7d30a372013-07-01 17:03:59 -07002570 /*
2571 * Flinging to delete - IN PROGRESS
2572 */
2573 private PointF isFlingingToDelete() {
2574 ViewConfiguration config = ViewConfiguration.get(getContext());
2575 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2576
2577 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2578 // Do a quick dot product test to ensure that we are flinging upwards
2579 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2580 mVelocityTracker.getYVelocity());
2581 PointF upVec = new PointF(0f, -1f);
2582 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2583 (vel.length() * upVec.length()));
2584 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2585 return vel;
2586 }
2587 }
2588 return null;
2589 }
2590
2591 /**
2592 * Creates an animation from the current drag view along its current velocity vector.
2593 * For this animation, the alpha runs for a fixed duration and we update the position
2594 * progressively.
2595 */
2596 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2597 private View mDragView;
2598 private PointF mVelocity;
2599 private Rect mFrom;
2600 private long mPrevTime;
2601 private float mFriction;
2602
2603 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2604
2605 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2606 long startTime, float friction) {
2607 mDragView = dragView;
2608 mVelocity = vel;
2609 mFrom = from;
2610 mPrevTime = startTime;
2611 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2612 }
2613
2614 @Override
2615 public void onAnimationUpdate(ValueAnimator animation) {
2616 float t = ((Float) animation.getAnimatedValue()).floatValue();
2617 long curTime = AnimationUtils.currentAnimationTimeMillis();
2618
2619 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2620 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2621
2622 mDragView.setTranslationX(mFrom.left);
2623 mDragView.setTranslationY(mFrom.top);
2624 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2625
2626 mVelocity.x *= mFriction;
2627 mVelocity.y *= mFriction;
2628 mPrevTime = curTime;
2629 }
2630 };
2631
2632 private static final int ANIM_TAG_KEY = 100;
2633
2634 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2635 return new Runnable() {
2636 @Override
2637 public void run() {
2638 int dragViewIndex = indexOfChild(dragView);
2639
2640 // For each of the pages around the drag view, animate them from the previous
2641 // position to the new position in the layout (as a result of the drag view moving
2642 // in the layout)
2643 // NOTE: We can make an assumption here because we have side-bound pages that we
2644 // will always have pages to animate in from the left
Adam Cohen6f127a62014-06-12 14:54:41 -07002645 getFreeScrollPageRange(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002646 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2647 boolean slideFromLeft = (isLastWidgetPage ||
2648 dragViewIndex > mTempVisiblePagesRange[0]);
2649
2650 // Setup the scroll to the correct page before we swap the views
2651 if (slideFromLeft) {
2652 snapToPageImmediately(dragViewIndex - 1);
2653 }
2654
2655 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2656 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2657 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2658 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2659 ArrayList<Animator> animations = new ArrayList<Animator>();
2660 for (int i = lowerIndex; i <= upperIndex; ++i) {
2661 View v = getChildAt(i);
2662 // dragViewIndex < pageUnderPointIndex, so after we remove the
2663 // drag view all subsequent views to pageUnderPointIndex will
2664 // shift down.
2665 int oldX = 0;
2666 int newX = 0;
2667 if (slideFromLeft) {
2668 if (i == 0) {
2669 // Simulate the page being offscreen with the page spacing
2670 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
Adam Cohen3b185e22013-10-29 14:45:58 -07002671 - mPageSpacing;
Adam Cohen7d30a372013-07-01 17:03:59 -07002672 } else {
2673 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2674 }
2675 newX = getViewportOffsetX() + getChildOffset(i);
2676 } else {
2677 oldX = getChildOffset(i) - getChildOffset(i - 1);
2678 newX = 0;
2679 }
2680
2681 // Animate the view translation from its old position to its new
2682 // position
2683 AnimatorSet anim = (AnimatorSet) v.getTag();
2684 if (anim != null) {
2685 anim.cancel();
2686 }
2687
2688 // Note: Hacky, but we want to skip any optimizations to not draw completely
2689 // hidden views
2690 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2691 v.setTranslationX(oldX - newX);
2692 anim = new AnimatorSet();
2693 anim.playTogether(
2694 ObjectAnimator.ofFloat(v, "translationX", 0f),
2695 ObjectAnimator.ofFloat(v, "alpha", 1f));
2696 animations.add(anim);
2697 v.setTag(ANIM_TAG_KEY, anim);
2698 }
2699
2700 AnimatorSet slideAnimations = new AnimatorSet();
2701 slideAnimations.playTogether(animations);
2702 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2703 slideAnimations.addListener(new AnimatorListenerAdapter() {
2704 @Override
2705 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002706 mDeferringForDelete = false;
2707 onEndReordering();
2708 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002709 }
2710 });
2711 slideAnimations.start();
2712
2713 removeView(dragView);
2714 onRemoveView(dragView, true);
2715 }
2716 };
2717 }
2718
2719 public void onFlingToDelete(PointF vel) {
2720 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2721
2722 // NOTE: Because it takes time for the first frame of animation to actually be
2723 // called and we expect the animation to be a continuation of the fling, we have
2724 // to account for the time that has elapsed since the fling finished. And since
2725 // we don't have a startDelay, we will always get call to update when we call
2726 // start() (which we want to ignore).
2727 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2728 private int mCount = -1;
2729 private long mStartTime;
2730 private float mOffset;
2731 /* Anonymous inner class ctor */ {
2732 mStartTime = startTime;
2733 }
2734
2735 @Override
2736 public float getInterpolation(float t) {
2737 if (mCount < 0) {
2738 mCount++;
2739 } else if (mCount == 0) {
2740 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2741 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2742 mCount++;
2743 }
2744 return Math.min(1f, mOffset + t);
2745 }
2746 };
2747
2748 final Rect from = new Rect();
2749 final View dragView = mDragView;
2750 from.left = (int) dragView.getTranslationX();
2751 from.top = (int) dragView.getTranslationY();
2752 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2753 from, startTime, FLING_TO_DELETE_FRICTION);
2754
2755 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2756
2757 // Create and start the animation
2758 ValueAnimator mDropAnim = new ValueAnimator();
2759 mDropAnim.setInterpolator(tInterpolator);
2760 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2761 mDropAnim.setFloatValues(0f, 1f);
2762 mDropAnim.addUpdateListener(updateCb);
2763 mDropAnim.addListener(new AnimatorListenerAdapter() {
2764 public void onAnimationEnd(Animator animation) {
2765 onAnimationEndRunnable.run();
2766 }
2767 });
2768 mDropAnim.start();
2769 mDeferringForDelete = true;
2770 }
2771
2772 /* Drag to delete */
2773 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2774 if (mDeleteDropTarget != null) {
2775 mAltTmpRect.set(0, 0, 0, 0);
2776 View parent = (View) mDeleteDropTarget.getParent();
2777 if (parent != null) {
2778 parent.getGlobalVisibleRect(mAltTmpRect);
2779 }
2780 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2781 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2782 return mTmpRect.contains(x, y);
2783 }
2784 return false;
2785 }
2786
2787 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2788
2789 private void onDropToDelete() {
2790 final View dragView = mDragView;
2791
2792 final float toScale = 0f;
2793 final float toAlpha = 0f;
2794
2795 // Create and start the complex animation
2796 ArrayList<Animator> animations = new ArrayList<Animator>();
2797 AnimatorSet motionAnim = new AnimatorSet();
2798 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2799 motionAnim.playTogether(
2800 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2801 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2802 animations.add(motionAnim);
2803
2804 AnimatorSet alphaAnim = new AnimatorSet();
2805 alphaAnim.setInterpolator(new LinearInterpolator());
2806 alphaAnim.playTogether(
2807 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2808 animations.add(alphaAnim);
2809
2810 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2811
2812 AnimatorSet anim = new AnimatorSet();
2813 anim.playTogether(animations);
2814 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2815 anim.addListener(new AnimatorListenerAdapter() {
2816 public void onAnimationEnd(Animator animation) {
2817 onAnimationEndRunnable.run();
2818 }
2819 });
2820 anim.start();
2821
2822 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002823 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002824
2825 /* Accessibility */
2826 @Override
2827 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2828 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002829 info.setScrollable(getPageCount() > 1);
2830 if (getCurrentPage() < getPageCount() - 1) {
2831 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2832 }
2833 if (getCurrentPage() > 0) {
2834 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2835 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002836 }
2837
2838 @Override
Alan Viverette254139a2013-10-08 13:13:46 -07002839 public void sendAccessibilityEvent(int eventType) {
2840 // Don't let the view send real scroll events.
2841 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2842 super.sendAccessibilityEvent(eventType);
2843 }
2844 }
2845
2846 @Override
Winson Chung6a0f57d2011-06-29 20:10:49 -07002847 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2848 super.onInitializeAccessibilityEvent(event);
2849 event.setScrollable(true);
Winson Chung6a0f57d2011-06-29 20:10:49 -07002850 }
2851
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002852 @Override
2853 public boolean performAccessibilityAction(int action, Bundle arguments) {
2854 if (super.performAccessibilityAction(action, arguments)) {
2855 return true;
2856 }
2857 switch (action) {
2858 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2859 if (getCurrentPage() < getPageCount() - 1) {
2860 scrollRight();
2861 return true;
2862 }
2863 } break;
2864 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2865 if (getCurrentPage() > 0) {
2866 scrollLeft();
2867 return true;
2868 }
2869 } break;
2870 }
2871 return false;
2872 }
2873
Adam Cohen0ffac432013-07-10 11:19:26 -07002874 protected String getCurrentPageDescription() {
2875 return String.format(getContext().getString(R.string.default_scroll_format),
2876 getNextPage() + 1, getChildCount());
2877 }
2878
Winson Chungd11265e2011-08-30 13:37:23 -07002879 @Override
2880 public boolean onHoverEvent(android.view.MotionEvent event) {
2881 return true;
2882 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002883}