blob: 6d750186512ee9770ce72c34ba62cf45c76218b2 [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 -070053import android.widget.Scroller;
54
Winson Chung6a0f57d2011-06-29 20:10:49 -070055import java.util.ArrayList;
56
Winson Chungc58497e2013-09-03 17:48:37 -070057interface Page {
58 public int getPageChildCount();
59 public View getChildOnPageAt(int i);
60 public void removeAllViewsOnPage();
61 public void removeViewOnPageAt(int i);
62 public int indexOfChildOnPage(View v);
63}
64
Winson Chung321e9ee2010-08-09 13:37:56 -070065/**
66 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070067 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070068 */
Michael Jurka8b805b12012-04-18 14:23:14 -070069public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070070 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070071 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070072 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070073
Winson Chung86f77532010-08-24 11:08:22 -070074 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070075 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070076
Adam Cohen7d30a372013-07-01 17:03:59 -070077 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070078 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070079 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070080
Adam Cohenb5ba0972011-09-07 18:02:31 -070081 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070082 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080083
Adam Cohenb64cb5a2011-02-15 13:53:42 -080084 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080085 // The page is moved more than halfway, automatically move to the next page on touch up.
86 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080087
Adam Cohen265b9a62011-12-07 14:37:18 -080088 // The following constants need to be scaled based on density. The scaled versions will be
89 // assigned to the corresponding member variables below.
90 private static final int FLING_THRESHOLD_VELOCITY = 500;
91 private static final int MIN_SNAP_VELOCITY = 1500;
92 private static final int MIN_FLING_VELOCITY = 250;
93
Adam Cohen7d30a372013-07-01 17:03:59 -070094 // We are disabling touch interaction of the widget region for factory ROM.
95 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070096 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070097 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070098
Adam Cohenf358a4b2013-07-23 16:47:31 -070099 private boolean mFreeScroll = false;
100 private int mFreeScrollMinScrollX = -1;
101 private int mFreeScrollMaxScrollX = -1;
102
Winson Chung8aad6102012-05-11 16:27:49 -0700103 static final int AUTOMATIC_PAGE_SPACING = -1;
104
Adam Cohen265b9a62011-12-07 14:37:18 -0800105 protected int mFlingThresholdVelocity;
106 protected int mMinFlingVelocity;
107 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700108
Adam Cohenb5ba0972011-09-07 18:02:31 -0700109 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700110 protected float mSmoothingTime;
111 protected float mTouchX;
112
113 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700114 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700115
116 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700117 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700118 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700119
Michael Jurka0142d492010-08-25 17:46:15 -0700120 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800121 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700122 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700123 private VelocityTracker mVelocityTracker;
124
Adam Cohen7d30a372013-07-01 17:03:59 -0700125 private float mParentDownMotionX;
126 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700127 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700128 private float mDownMotionY;
129 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700130 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800131 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800132 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800133 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800134 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700135 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700136
Adam Cohendbdff6b2013-09-18 19:09:15 -0700137 private boolean mCancelTap;
138
Adam Cohenedb40762013-07-18 16:45:45 -0700139 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140
Michael Jurka0142d492010-08-25 17:46:15 -0700141 protected final static int TOUCH_STATE_REST = 0;
142 protected final static int TOUCH_STATE_SCROLLING = 1;
143 protected final static int TOUCH_STATE_PREV_PAGE = 2;
144 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700145 protected final static int TOUCH_STATE_REORDERING = 4;
146
Adam Cohene45440e2010-10-14 18:33:38 -0700147 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700148
Michael Jurka0142d492010-08-25 17:46:15 -0700149 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700150 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700151
Michael Jurka0142d492010-08-25 17:46:15 -0700152 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700153
Michael Jurka7426c422010-11-11 15:23:47 -0800154 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700155 private int mPagingTouchSlop;
156 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700157 protected int mPageSpacing;
158 protected int mPageLayoutPaddingTop;
159 protected int mPageLayoutPaddingBottom;
160 protected int mPageLayoutPaddingLeft;
161 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700162 protected int mPageLayoutWidthGap;
163 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700164 protected int mCellCountX = 0;
165 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700166 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800167 protected boolean mAllowOverScroll = true;
168 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800169 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700170 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurka8b805b12012-04-18 14:23:14 -0700172 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800173 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
174 // the screens from continuing to translate beyond the normal bounds.
175 protected int mOverScrollX;
176
Michael Jurka5f1c5092010-09-03 14:15:02 -0700177 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700178
Michael Jurka5f1c5092010-09-03 14:15:02 -0700179 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700180
Winson Chung86f77532010-08-24 11:08:22 -0700181 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700182
Michael Jurkae326f182011-11-21 14:05:46 -0800183 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700184
Michael Jurka0142d492010-08-25 17:46:15 -0700185 // If true, syncPages and syncPageItems will be called to refresh pages
186 protected boolean mContentIsRefreshable = true;
187
188 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700189 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700190
191 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
192 // to switch to a new page
193 protected boolean mUsePagingTouchSlop = true;
194
Michael Jurka8b805b12012-04-18 14:23:14 -0700195 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700196 // (SmoothPagedView does this)
197 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700198 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700199
Patrick Dubroy1262e362010-10-06 15:49:50 -0700200 protected boolean mIsPageMoving = false;
201
Winson Chungf0ea4d32011-06-06 14:27:16 -0700202 // All syncs and layout passes are deferred until data is ready.
203 protected boolean mIsDataReady = false;
204
Adam Cohen7d30a372013-07-01 17:03:59 -0700205 protected boolean mAllowLongPress = true;
206
Winson Chungd2be3812013-07-16 11:11:32 -0700207 // Page Indicator
208 private int mPageIndicatorViewId;
209 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700210 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700211
Adam Cohen7d30a372013-07-01 17:03:59 -0700212 // The viewport whether the pages are to be contained (the actual view may be larger than the
213 // viewport)
214 private Rect mViewport = new Rect();
215
216 // Reordering
217 // We use the min scale to determine how much to expand the actually PagedView measured
218 // dimensions such that when we are zoomed out, the view is not clipped
219 private int REORDERING_DROP_REPOSITION_DURATION = 200;
220 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
221 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700222 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700223 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700224 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700225 protected View mDragView;
226 protected AnimatorSet mZoomInOutAnim;
227 private Runnable mSidePageHoverRunnable;
228 private int mSidePageHoverIndex = -1;
229 // This variable's scope is only for the duration of startReordering() and endReordering()
230 private boolean mReorderingStarted = false;
231 // This variable's scope is for the duration of startReordering() and after the zoomIn()
232 // animation after endReordering()
233 private boolean mIsReordering;
234 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
235 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
236 private int mPostReorderingPreZoomInRemainingAnimationCount;
237 private Runnable mPostReorderingPreZoomInRunnable;
238
Adam Cohen7d30a372013-07-01 17:03:59 -0700239 // Convenience/caching
240 private Matrix mTmpInvMatrix = new Matrix();
241 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700242 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700243 private Rect mTmpRect = new Rect();
244 private Rect mAltTmpRect = new Rect();
245
246 // Fling to delete
247 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
248 private float FLING_TO_DELETE_FRICTION = 0.035f;
249 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
250 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
251 protected int mFlingToDeleteThresholdVelocity = -1400;
252 // Drag to delete
253 private boolean mDeferringForDelete = false;
254 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
255 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
256
257 // Drop to delete
258 private View mDeleteDropTarget;
259
260 private boolean mAutoComputePageSpacing = false;
261 private boolean mRecomputePageSpacing = false;
262
263 // Bouncer
264 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700265
John Spurlock77e1f472013-09-11 10:09:51 -0400266 protected final Rect mInsets = new Rect();
267
Winson Chung86f77532010-08-24 11:08:22 -0700268 public interface PageSwitchListener {
269 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700270 }
271
Winson Chung321e9ee2010-08-09 13:37:56 -0700272 public PagedView(Context context) {
273 this(context, null);
274 }
275
276 public PagedView(Context context, AttributeSet attrs) {
277 this(context, attrs, 0);
278 }
279
280 public PagedView(Context context, AttributeSet attrs, int defStyle) {
281 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700282
Adam Cohen9c4949e2010-10-05 12:27:22 -0700283 TypedArray a = context.obtainStyledAttributes(attrs,
284 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800285 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700286 if (mPageSpacing < 0) {
287 mAutoComputePageSpacing = mRecomputePageSpacing = true;
288 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700289 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800290 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700291 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800292 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700293 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800294 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700295 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800296 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700297 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700298 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700299 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700300 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700301 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700302 a.recycle();
303
Winson Chung321e9ee2010-08-09 13:37:56 -0700304 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700305 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700306 }
307
308 /**
309 * Initializes various states for this workspace.
310 */
Michael Jurka0142d492010-08-25 17:46:15 -0700311 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700312 mDirtyPageContent = new ArrayList<Boolean>();
313 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800314 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700315 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700316 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700317
318 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700319 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700320 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
321 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700322 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800323
Adam Cohen7d30a372013-07-01 17:03:59 -0700324 // Scale the fling-to-delete threshold by the density
325 mFlingToDeleteThresholdVelocity =
326 (int) (mFlingToDeleteThresholdVelocity * mDensity);
327
Adam Cohen265b9a62011-12-07 14:37:18 -0800328 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
329 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
330 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700331 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700332 }
333
Winson Chungd2be3812013-07-16 11:11:32 -0700334 protected void onAttachedToWindow() {
335 // Hook up the page indicator
336 ViewGroup parent = (ViewGroup) getParent();
337 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
338 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700339 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700340
Winson Chung7819a562013-09-19 15:55:45 -0700341 ArrayList<PageIndicator.PageMarkerResources> markers =
342 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700343 for (int i = 0; i < getChildCount(); ++i) {
344 markers.add(getPageIndicatorMarker(i));
345 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700346
Winson Chungc58497e2013-09-03 17:48:37 -0700347 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700348 }
349 }
350
351 protected void onDetachedFromWindow() {
352 // Unhook the page indicator
353 mPageIndicator = null;
354 }
355
Adam Cohen7d30a372013-07-01 17:03:59 -0700356 void setDeleteDropTarget(View v) {
357 mDeleteDropTarget = v;
358 }
359
360 // Convenience methods to map points from self to parent and vice versa
361 float[] mapPointFromViewToParent(View v, float x, float y) {
362 mTmpPoint[0] = x;
363 mTmpPoint[1] = y;
364 v.getMatrix().mapPoints(mTmpPoint);
365 mTmpPoint[0] += v.getLeft();
366 mTmpPoint[1] += v.getTop();
367 return mTmpPoint;
368 }
369 float[] mapPointFromParentToView(View v, float x, float y) {
370 mTmpPoint[0] = x - v.getLeft();
371 mTmpPoint[1] = y - v.getTop();
372 v.getMatrix().invert(mTmpInvMatrix);
373 mTmpInvMatrix.mapPoints(mTmpPoint);
374 return mTmpPoint;
375 }
376
377 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700378 if (mDragView != null) {
379 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
380 (mDragViewBaselineLeft - mDragView.getLeft());
381 float y = mLastMotionY - mDownMotionY;
382 mDragView.setTranslationX(x);
383 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700384
Adam Cohenf358a4b2013-07-23 16:47:31 -0700385 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
386 + x + ", " + y);
387 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700388 }
389
390 public void setMinScale(float f) {
391 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700392 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700393 requestLayout();
394 }
395
396 @Override
397 public void setScaleX(float scaleX) {
398 super.setScaleX(scaleX);
399 if (isReordering(true)) {
400 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
401 mLastMotionX = p[0];
402 mLastMotionY = p[1];
403 updateDragViewTranslationDuringDrag();
404 }
405 }
406
407 // Convenience methods to get the actual width/height of the PagedView (since it is measured
408 // to be larger to account for the minimum possible scale)
409 int getViewportWidth() {
410 return mViewport.width();
411 }
412 int getViewportHeight() {
413 return mViewport.height();
414 }
415
416 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
417 // PagedView both horizontally and vertically
418 int getViewportOffsetX() {
419 return (getMeasuredWidth() - getViewportWidth()) / 2;
420 }
421
422 int getViewportOffsetY() {
423 return (getMeasuredHeight() - getViewportHeight()) / 2;
424 }
425
Adam Cohenedb40762013-07-18 16:45:45 -0700426 PageIndicator getPageIndicator() {
427 return mPageIndicator;
428 }
Winson Chung7819a562013-09-19 15:55:45 -0700429 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
430 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700431 }
Adam Cohenedb40762013-07-18 16:45:45 -0700432
Winson Chung86f77532010-08-24 11:08:22 -0700433 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
434 mPageSwitchListener = pageSwitchListener;
435 if (mPageSwitchListener != null) {
436 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700437 }
438 }
439
440 /**
Winson Chung52aee602013-01-30 12:01:02 -0800441 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
442 */
443 public boolean isLayoutRtl() {
444 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
445 }
446
447 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700448 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
449 * out pages.
450 */
451 protected void setDataIsReady() {
452 mIsDataReady = true;
453 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700454
Winson Chungf0ea4d32011-06-06 14:27:16 -0700455 protected boolean isDataReady() {
456 return mIsDataReady;
457 }
458
459 /**
Winson Chung86f77532010-08-24 11:08:22 -0700460 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700461 *
Winson Chung86f77532010-08-24 11:08:22 -0700462 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700463 */
Winson Chung86f77532010-08-24 11:08:22 -0700464 int getCurrentPage() {
465 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700466 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700467
Winson Chung360e63f2012-04-27 13:48:05 -0700468 int getNextPage() {
469 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
470 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700471
Winson Chung86f77532010-08-24 11:08:22 -0700472 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700473 return getChildCount();
474 }
475
Winson Chung86f77532010-08-24 11:08:22 -0700476 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700477 return getChildAt(index);
478 }
479
Adam Cohenae4f1552011-10-20 00:15:42 -0700480 protected int indexToPage(int index) {
481 return index;
482 }
483
Winson Chung321e9ee2010-08-09 13:37:56 -0700484 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800485 * Updates the scroll of the current page immediately to its final scroll position. We use this
486 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
487 * the previous tab page.
488 */
489 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700490 // If the current page is invalid, just reset the scroll position to zero
491 int newX = 0;
492 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700493 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700494 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800495 scrollTo(newX, 0);
496 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800497 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800498 }
499
500 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700501 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
502 * ends, {@link #resumeScrolling()} should be called, along with
503 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
504 */
505 void pauseScrolling() {
506 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700507 }
508
509 /**
510 * Enables scrolling again.
511 * @see #pauseScrolling()
512 */
513 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700514 }
515 /**
Winson Chung86f77532010-08-24 11:08:22 -0700516 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700517 */
Winson Chung86f77532010-08-24 11:08:22 -0700518 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800519 if (!mScroller.isFinished()) {
520 mScroller.abortAnimation();
Adam Cohen97d53112013-10-01 11:07:24 -0700521 // We need to clean up the next page here to avoid computeScrollHelper from
522 // updating current page on the pass.
523 mNextPage = INVALID_PAGE;
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800524 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800525 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
526 // the default
527 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800528 return;
529 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700530
Adam Cohene61a9a22013-06-11 15:45:31 -0700531 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700532 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700533 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700534 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800535 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700536 }
537
Winson Chung8c87cd82013-07-23 16:20:10 -0700538 /**
539 * The restore page will be set in place of the current page at the next (likely first)
540 * layout.
541 */
542 void setRestorePage(int restorePage) {
543 mRestorePage = restorePage;
544 }
545
Michael Jurka0142d492010-08-25 17:46:15 -0700546 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700547 if (mPageSwitchListener != null) {
548 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700549 }
Winson Chungd2be3812013-07-16 11:11:32 -0700550
551 // Update the page indicator (when we aren't reordering)
552 if (mPageIndicator != null && !isReordering(false)) {
553 mPageIndicator.setActiveMarker(getNextPage());
554 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700555 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800556 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700557 if (!mIsPageMoving) {
558 mIsPageMoving = true;
559 onPageBeginMoving();
560 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700561 }
562
Michael Jurkace7e05f2011-02-01 22:02:35 -0800563 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700564 if (mIsPageMoving) {
565 mIsPageMoving = false;
566 onPageEndMoving();
567 }
Michael Jurka0142d492010-08-25 17:46:15 -0700568 }
569
Adam Cohen26976d92011-03-22 15:33:33 -0700570 protected boolean isPageMoving() {
571 return mIsPageMoving;
572 }
573
Michael Jurka0142d492010-08-25 17:46:15 -0700574 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700575 protected void onPageBeginMoving() {
576 }
577
578 // a method that subclasses can override to add behavior
579 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700580 }
581
Winson Chung321e9ee2010-08-09 13:37:56 -0700582 /**
Winson Chung86f77532010-08-24 11:08:22 -0700583 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700584 *
585 * @param l The listener used to respond to long clicks.
586 */
587 @Override
588 public void setOnLongClickListener(OnLongClickListener l) {
589 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700590 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700591 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700592 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700593 }
Adam Cohen1697b792013-09-17 19:08:21 -0700594 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700595 }
596
597 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800598 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700599 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800600 }
601
602 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700603 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700604 // In free scroll mode, we clamp the scrollX
605 if (mFreeScroll) {
606 x = Math.min(x, mFreeScrollMaxScrollX);
607 x = Math.max(x, mFreeScrollMinScrollX);
608 }
609
Adam Cohen0ffac432013-07-10 11:19:26 -0700610 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800611 mUnboundedScrollX = x;
612
Adam Cohen0ffac432013-07-10 11:19:26 -0700613 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
614 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
615 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800616 super.scrollTo(0, y);
617 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700618 if (isRtl) {
619 overScroll(x - mMaxScrollX);
620 } else {
621 overScroll(x);
622 }
Adam Cohen68d73932010-11-15 10:50:58 -0800623 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700624 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800625 super.scrollTo(mMaxScrollX, y);
626 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700627 if (isRtl) {
628 overScroll(x);
629 } else {
630 overScroll(x - mMaxScrollX);
631 }
Adam Cohen68d73932010-11-15 10:50:58 -0800632 }
633 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800634 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800635 super.scrollTo(x, y);
636 }
637
Michael Jurka0142d492010-08-25 17:46:15 -0700638 mTouchX = x;
639 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700640
641 // Update the last motion events when scrolling
642 if (isReordering(true)) {
643 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
644 mLastMotionX = p[0];
645 mLastMotionY = p[1];
646 updateDragViewTranslationDuringDrag();
647 }
Michael Jurka0142d492010-08-25 17:46:15 -0700648 }
649
650 // we moved this functionality to a helper function so SmoothPagedView can reuse it
651 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700652 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700653 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700654 if (getScrollX() != mScroller.getCurrX()
655 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700656 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700657 float scaleX = mFreeScroll ? getScaleX() : 1f;
658 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
659 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700660 }
Michael Jurka0142d492010-08-25 17:46:15 -0700661 invalidate();
662 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700663 } else if (mNextPage != INVALID_PAGE) {
664 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700665 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700666 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700667
Winson Chung9c0565f2013-07-19 13:49:06 -0700668 // Load the associated pages if necessary
669 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
670 loadAssociatedPages(mCurrentPage);
671 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
672 }
673
Adam Cohen73aa9752010-11-24 16:26:58 -0800674 // We don't want to trigger a page end moving unless the page has settled
675 // and the user has stopped scrolling
676 if (mTouchState == TOUCH_STATE_REST) {
677 pageEndMoving();
678 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700679
Adam Cohen7d30a372013-07-01 17:03:59 -0700680 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700681 // Notify the user when the page changes
682 AccessibilityManager accessibilityManager = (AccessibilityManager)
683 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
684 if (accessibilityManager.isEnabled()) {
685 AccessibilityEvent ev =
686 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
687 ev.getText().add(getCurrentPageDescription());
688 sendAccessibilityEventUnchecked(ev);
689 }
Michael Jurka0142d492010-08-25 17:46:15 -0700690 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700691 }
Michael Jurka0142d492010-08-25 17:46:15 -0700692 return false;
693 }
694
695 @Override
696 public void computeScroll() {
697 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700698 }
699
Adam Cohen7d30a372013-07-01 17:03:59 -0700700 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
701 return mTopAlignPageWhenShrinkingForBouncer;
702 }
703
Adam Cohen96d30a12013-07-16 18:13:21 -0700704 public static class LayoutParams extends ViewGroup.LayoutParams {
705 public boolean isFullScreenPage = false;
706
707 /**
708 * {@inheritDoc}
709 */
710 public LayoutParams(int width, int height) {
711 super(width, height);
712 }
713
714 public LayoutParams(ViewGroup.LayoutParams source) {
715 super(source);
716 }
717 }
718
719 protected LayoutParams generateDefaultLayoutParams() {
720 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
721 }
722
Adam Cohenedb40762013-07-18 16:45:45 -0700723 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700724 LayoutParams lp = generateDefaultLayoutParams();
725 lp.isFullScreenPage = true;
726 super.addView(page, 0, lp);
727 }
728
Adam Cohen410f3cd2013-09-22 12:09:32 -0700729 public int getNormalChildHeight() {
730 return mNormalChildHeight;
731 }
732
Winson Chung321e9ee2010-08-09 13:37:56 -0700733 @Override
734 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700735 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700736 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
737 return;
738 }
739
Adam Cohen7d30a372013-07-01 17:03:59 -0700740 // We measure the dimensions of the PagedView to be larger than the pages so that when we
741 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700742 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
743 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
744 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700745 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700746 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
747 // viewport, we can be at most one and a half screens offset once we scale down
748 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700749 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700750
Winson Chungc58497e2013-09-03 17:48:37 -0700751 int parentWidthSize, parentHeightSize;
752 int scaledWidthSize, scaledHeightSize;
753 if (mUseMinScale) {
754 parentWidthSize = (int) (1.5f * maxSize);
755 parentHeightSize = maxSize;
756 scaledWidthSize = (int) (parentWidthSize / mMinScale);
757 scaledHeightSize = (int) (parentHeightSize / mMinScale);
758 } else {
759 scaledWidthSize = widthSize;
760 scaledHeightSize = heightSize;
761 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700762 mViewport.set(0, 0, widthSize, heightSize);
763
764 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
765 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
766 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700767 }
768
Winson Chung8aad6102012-05-11 16:27:49 -0700769 // Return early if we aren't given a proper dimension
770 if (widthSize <= 0 || heightSize <= 0) {
771 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
772 return;
773 }
774
Adam Lesinski6b879f02010-11-04 16:15:23 -0700775 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
776 * of the All apps view on XLarge displays to not take up more space then it needs. Width
777 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
778 * each page to have the same width.
779 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700780 final int verticalPadding = getPaddingTop() + getPaddingBottom();
781 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700782
783 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700784 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700785 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700786 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
787 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
788 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
789 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700790 final int childCount = getChildCount();
791 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700792 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700793 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700794 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
795
796 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700797 int childHeightMode;
798 int childWidth;
799 int childHeight;
800
801 if (!lp.isFullScreenPage) {
802 if (lp.width == LayoutParams.WRAP_CONTENT) {
803 childWidthMode = MeasureSpec.AT_MOST;
804 } else {
805 childWidthMode = MeasureSpec.EXACTLY;
806 }
807
808 if (lp.height == LayoutParams.WRAP_CONTENT) {
809 childHeightMode = MeasureSpec.AT_MOST;
810 } else {
811 childHeightMode = MeasureSpec.EXACTLY;
812 }
813
814 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400815 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700816 mNormalChildHeight = childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700817
Michael Jurka5f1c5092010-09-03 14:15:02 -0700818 } else {
819 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700820 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700821
Winson Chungc58497e2013-09-03 17:48:37 -0700822 if (mUseMinScale) {
823 childWidth = getViewportWidth();
824 childHeight = getViewportHeight();
825 } else {
826 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
827 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
828 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700829 }
830
831 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700832 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
833 final int childHeightMeasureSpec =
834 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700835 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700836 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700837 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700838
Winson Chunga128a7b2012-04-30 15:23:15 -0700839 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700840 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700841 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700842 // The gap between pages in the PagedView should be equal to the gap from the page
843 // to the edge of the screen (so it is not visible in the current screen). To
844 // account for unequal padding on each side of the paged view, we take the maximum
845 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700846 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700847 int spacing = Math.max(offset, widthSize - offset -
848 getChildAt(0).getMeasuredWidth());
849 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700850 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700851 }
852 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700853 }
854
Adam Cohen60b07122011-11-14 17:26:06 -0800855 public void setPageSpacing(int pageSpacing) {
856 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700857 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800858 }
859
Winson Chung321e9ee2010-08-09 13:37:56 -0700860 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700861 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700862 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700863 return;
864 }
865
Winson Chung785d2eb2011-04-14 16:08:02 -0700866 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700867 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700868
Adam Cohenedb40762013-07-18 16:45:45 -0700869 int screenWidth = getViewportWidth();
870
Adam Cohen7d30a372013-07-01 17:03:59 -0700871 int offsetX = getViewportOffsetX();
872 int offsetY = getViewportOffsetY();
873
874 // Update the viewport offsets
875 mViewport.offset(offsetX, offsetY);
876
Adam Cohen0ffac432013-07-10 11:19:26 -0700877 final boolean isRtl = isLayoutRtl();
878
879 final int startIndex = isRtl ? childCount - 1 : 0;
880 final int endIndex = isRtl ? -1 : childCount;
881 final int delta = isRtl ? -1 : 1;
882
Adam Cohen7d30a372013-07-01 17:03:59 -0700883 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700884 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
885
886 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
887 mPageScrolls = new int[getChildCount()];
888 }
889
Adam Cohen0ffac432013-07-10 11:19:26 -0700890 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700891 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700892 LayoutParams lp = (LayoutParams) child.getLayoutParams();
893 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700894 if (lp.isFullScreenPage) {
895 childTop = offsetY;
896 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400897 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700898 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400899 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700900 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700901 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700902
Winson Chung321e9ee2010-08-09 13:37:56 -0700903 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700904 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700905 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800906
Winson Chung785d2eb2011-04-14 16:08:02 -0700907 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700908 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800909 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700910
911 // We assume the left and right padding are equal, and hence center the pages
912 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700913 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700914 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
915
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700916 if (i != endIndex - delta) {
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700917 childLeft += childWidth + scrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700918 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700919 childLeft += nextScrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700920 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700921 }
922 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700923
924 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
925 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800926 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700927 setHorizontalScrollBarEnabled(true);
928 mFirstLayout = false;
929 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700930
931 if (childCount > 0) {
932 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700933 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700934 } else {
935 mMaxScrollX = 0;
936 }
937
938 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
939 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700940 if (mRestorePage > -1) {
941 setCurrentPage(mRestorePage);
942 mRestorePage = -1;
943 } else {
944 setCurrentPage(getNextPage());
945 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700946 }
947 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700948
949 if (isReordering(true)) {
950 updateDragViewTranslationDuringDrag();
951 }
Winson Chunge3193b92010-09-10 11:44:42 -0700952 }
953
Adam Cohenf34bab52010-09-30 14:11:56 -0700954 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700955 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
956
957 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700958 for (int i = 0; i < getChildCount(); i++) {
959 View child = getChildAt(i);
960 if (child != null) {
961 float scrollProgress = getScrollProgress(screenCenter, child, i);
962 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800963 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700964 }
965 }
966 invalidate();
967 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700968 }
969
Winson Chungc58497e2013-09-03 17:48:37 -0700970 protected void enablePagedViewAnimations() {
971 mAllowPagedViewAnimations = true;
972
973 }
974 protected void disablePagedViewAnimations() {
975 mAllowPagedViewAnimations = false;
976 }
977
Winson Chunge3193b92010-09-10 11:44:42 -0700978 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700979 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700980 // Update the page indicator, we don't update the page indicator as we
981 // add/remove pages
982 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700983 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -0700984 mPageIndicator.addMarker(pageIndex,
985 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -0700986 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700987 }
988
Adam Cohen2591f6a2011-10-25 14:36:40 -0700989 // This ensures that when children are added, they get the correct transforms / alphas
990 // in accordance with any scroll effects.
991 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700992 mRecomputePageSpacing = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -0700993 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -0700994 invalidate();
995 }
996
Michael Jurka8b805b12012-04-18 14:23:14 -0700997 @Override
998 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700999 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001000 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001001 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001002 }
1003
Winson Chungd2be3812013-07-16 11:11:32 -07001004 private void removeMarkerForView(int index) {
1005 // Update the page indicator, we don't update the page indicator as we
1006 // add/remove pages
1007 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001008 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001009 }
1010 }
1011
1012 @Override
1013 public void removeView(View v) {
1014 // XXX: We should find a better way to hook into this before the view
1015 // gets removed form its parent...
1016 removeMarkerForView(indexOfChild(v));
1017 super.removeView(v);
1018 }
1019 @Override
1020 public void removeViewInLayout(View v) {
1021 // XXX: We should find a better way to hook into this before the view
1022 // gets removed form its parent...
1023 removeMarkerForView(indexOfChild(v));
1024 super.removeViewInLayout(v);
1025 }
1026 @Override
1027 public void removeViewAt(int index) {
1028 // XXX: We should find a better way to hook into this before the view
1029 // gets removed form its parent...
1030 removeViewAt(index);
1031 super.removeViewAt(index);
1032 }
1033 @Override
1034 public void removeAllViewsInLayout() {
1035 // Update the page indicator, we don't update the page indicator as we
1036 // add/remove pages
1037 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001038 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001039 }
1040
1041 super.removeAllViewsInLayout();
1042 }
1043
Adam Cohen73894962011-10-31 13:17:17 -07001044 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001045 if (index < 0 || index > getChildCount() - 1) return 0;
1046
Adam Cohenf698c6e2013-07-17 18:44:25 -07001047 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001048
Adam Cohenf698c6e2013-07-17 18:44:25 -07001049 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001050 }
1051
Adam Cohenf358a4b2013-07-23 16:47:31 -07001052 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001053 range[0] = 0;
1054 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001055 }
1056
Michael Jurkadde558b2011-11-09 22:09:06 -08001057 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001058 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001059 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001060
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001061 range[0] = -1;
1062 range[1] = -1;
1063
Michael Jurkac4fb9172010-09-02 17:19:20 -07001064 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001065 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001066 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001067
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001068 int count = getChildCount();
1069 for (int i = 0; i < count; i++) {
1070 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001071
Winson Chungc9ca2982013-07-19 12:07:38 -07001072 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001073 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001074 if (mTmpIntPoint[0] > viewportWidth) {
1075 if (range[0] == -1) {
1076 continue;
1077 } else {
1078 break;
1079 }
1080 }
1081
Adam Cohen6a678da2013-09-24 10:58:01 -07001082 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001083 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1084 if (mTmpIntPoint[0] < 0) {
1085 if (range[0] == -1) {
1086 continue;
1087 } else {
1088 break;
1089 }
1090 }
1091 curScreen = i;
1092 if (range[0] < 0) {
1093 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001094 }
1095 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001096
1097 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001098 } else {
1099 range[0] = -1;
1100 range[1] = -1;
1101 }
1102 }
1103
Michael Jurka920d7f42012-05-14 16:29:55 -07001104 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001105 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001106 }
1107
Michael Jurkadde558b2011-11-09 22:09:06 -08001108 @Override
1109 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001110 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001111 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1112 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001113 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001114
1115 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001116 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1117 // set it for the next frame
1118 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001119 screenScrolled(screenCenter);
1120 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001121 }
1122
1123 // Find out which screens are visible; as an optimization we only call draw on them
1124 final int pageCount = getChildCount();
1125 if (pageCount > 0) {
1126 getVisiblePages(mTempVisiblePagesRange);
1127 final int leftScreen = mTempVisiblePagesRange[0];
1128 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001129 if (leftScreen != -1 && rightScreen != -1) {
1130 final long drawingTime = getDrawingTime();
1131 // Clip to the bounds
1132 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001133 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1134 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001135
Adam Cohen7d30a372013-07-01 17:03:59 -07001136 // Draw all the children, leaving the drag view for last
1137 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001138 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001139 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001140 if (mForceDrawAllChildrenNextFrame ||
1141 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001142 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001143 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001144 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001145 // Draw the drag view on top (if there is one)
1146 if (mDragView != null) {
1147 drawChild(canvas, mDragView, drawingTime);
1148 }
1149
Michael Jurka5e368ff2012-05-14 23:13:15 -07001150 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001151 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001152 }
Michael Jurka0142d492010-08-25 17:46:15 -07001153 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001154 }
1155
1156 @Override
1157 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001158 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001159 if (page != mCurrentPage || !mScroller.isFinished()) {
1160 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001161 return true;
1162 }
1163 return false;
1164 }
1165
1166 @Override
1167 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001168 int focusablePage;
1169 if (mNextPage != INVALID_PAGE) {
1170 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001171 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001172 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001173 }
Winson Chung86f77532010-08-24 11:08:22 -07001174 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001175 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001176 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001177 }
1178 return false;
1179 }
1180
1181 @Override
1182 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001183 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001184 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001185 if (getCurrentPage() > 0) {
1186 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001187 return true;
1188 }
1189 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001190 if (getCurrentPage() < getPageCount() - 1) {
1191 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001192 return true;
1193 }
1194 }
1195 return super.dispatchUnhandledMove(focused, direction);
1196 }
1197
1198 @Override
1199 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001200 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001201 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001202 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001203 }
1204 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001205 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001206 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001207 }
1208 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001209 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001210 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001211 }
1212 }
1213 }
1214
1215 /**
1216 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001217 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001218 *
Winson Chung86f77532010-08-24 11:08:22 -07001219 * This happens when live folders requery, and if they're off page, they
1220 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001221 */
1222 @Override
1223 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001224 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001225 View v = focused;
1226 while (true) {
1227 if (v == current) {
1228 super.focusableViewAvailable(focused);
1229 return;
1230 }
1231 if (v == this) {
1232 return;
1233 }
1234 ViewParent parent = v.getParent();
1235 if (parent instanceof View) {
1236 v = (View)v.getParent();
1237 } else {
1238 return;
1239 }
1240 }
1241 }
1242
1243 /**
1244 * {@inheritDoc}
1245 */
1246 @Override
1247 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1248 if (disallowIntercept) {
1249 // We need to make sure to cancel our long press if
1250 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001251 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001252 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001253 }
1254 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1255 }
1256
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001257 /**
1258 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1259 */
1260 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001261 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001262 if (isLayoutRtl()) {
1263 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001264 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001265 }
Adam Cohenedb40762013-07-18 16:45:45 -07001266 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001267 }
1268
1269 /**
1270 * Return true if a tap at (x, y) should trigger a flip to the next page.
1271 */
1272 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001273 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001274 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001275 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001276 }
1277 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001278 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001279 }
Winson Chung52aee602013-01-30 12:01:02 -08001280
Adam Cohen7d30a372013-07-01 17:03:59 -07001281 /** Returns whether x and y originated within the buffered viewport */
1282 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1283 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1284 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1285 return mTmpRect.contains(x, y);
1286 }
1287
Winson Chung321e9ee2010-08-09 13:37:56 -07001288 @Override
1289 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001290 if (DISABLE_TOUCH_INTERACTION) {
1291 return false;
1292 }
1293
Winson Chung321e9ee2010-08-09 13:37:56 -07001294 /*
1295 * This method JUST determines whether we want to intercept the motion.
1296 * If we return true, onTouchEvent will be called and we do the actual
1297 * scrolling there.
1298 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001299 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001300
Winson Chung45e1d6e2010-11-09 17:19:49 -08001301 // Skip touch handling if there are no pages to swipe
1302 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1303
Winson Chung321e9ee2010-08-09 13:37:56 -07001304 /*
1305 * Shortcut the most recurring case: the user is in the dragging
1306 * state and he is moving his finger. We want to intercept this
1307 * motion.
1308 */
1309 final int action = ev.getAction();
1310 if ((action == MotionEvent.ACTION_MOVE) &&
1311 (mTouchState == TOUCH_STATE_SCROLLING)) {
1312 return true;
1313 }
1314
Winson Chung321e9ee2010-08-09 13:37:56 -07001315 switch (action & MotionEvent.ACTION_MASK) {
1316 case MotionEvent.ACTION_MOVE: {
1317 /*
1318 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1319 * whether the user has moved far enough from his original down touch.
1320 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001321 if (mActivePointerId != INVALID_POINTER) {
1322 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001323 }
1324 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1325 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1326 // i.e. fall through to the next case (don't break)
1327 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1328 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001329 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001330 }
1331
1332 case MotionEvent.ACTION_DOWN: {
1333 final float x = ev.getX();
1334 final float y = ev.getY();
1335 // Remember location of down touch
1336 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001337 mDownMotionY = y;
1338 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001339 mLastMotionX = x;
1340 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001341 float[] p = mapPointFromViewToParent(this, x, y);
1342 mParentDownMotionX = p[0];
1343 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001344 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001345 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001346 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001347
Winson Chung321e9ee2010-08-09 13:37:56 -07001348 /*
1349 * If being flinged and user touches the screen, initiate drag;
1350 * otherwise don't. mScroller.isFinished should be false when
1351 * being flinged.
1352 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001353 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001354 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1355 if (finishedScrolling) {
1356 mTouchState = TOUCH_STATE_REST;
1357 mScroller.abortAnimation();
1358 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001359 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1360 mTouchState = TOUCH_STATE_SCROLLING;
1361 } else {
1362 mTouchState = TOUCH_STATE_REST;
1363 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001364 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001365
Winson Chung86f77532010-08-24 11:08:22 -07001366 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001368 if (!DISABLE_TOUCH_SIDE_PAGES) {
1369 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1370 if (getChildCount() > 0) {
1371 if (hitsPreviousPage(x, y)) {
1372 mTouchState = TOUCH_STATE_PREV_PAGE;
1373 } else if (hitsNextPage(x, y)) {
1374 mTouchState = TOUCH_STATE_NEXT_PAGE;
1375 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 }
1377 }
1378 }
1379 break;
1380 }
1381
Winson Chung321e9ee2010-08-09 13:37:56 -07001382 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001383 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001384 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001385 break;
1386
1387 case MotionEvent.ACTION_POINTER_UP:
1388 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001389 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001390 break;
1391 }
1392
1393 /*
1394 * The only time we want to intercept motion events is if we are in the
1395 * drag mode.
1396 */
1397 return mTouchState != TOUCH_STATE_REST;
1398 }
1399
Adam Cohenf8d28232011-02-01 21:47:00 -08001400 protected void determineScrollingStart(MotionEvent ev) {
1401 determineScrollingStart(ev, 1.0f);
1402 }
1403
Winson Chung321e9ee2010-08-09 13:37:56 -07001404 /*
1405 * Determines if we should change the touch state to start scrolling after the
1406 * user moves their touch point too far.
1407 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001408 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001409 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001410 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001411 if (pointerIndex == -1) return;
1412
1413 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001414 final float x = ev.getX(pointerIndex);
1415 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001416 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1417
Winson Chung321e9ee2010-08-09 13:37:56 -07001418 final int xDiff = (int) Math.abs(x - mLastMotionX);
1419 final int yDiff = (int) Math.abs(y - mLastMotionY);
1420
Adam Cohenf8d28232011-02-01 21:47:00 -08001421 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001422 boolean xPaged = xDiff > mPagingTouchSlop;
1423 boolean xMoved = xDiff > touchSlop;
1424 boolean yMoved = yDiff > touchSlop;
1425
Adam Cohenf8d28232011-02-01 21:47:00 -08001426 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001427 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001428 // Scroll if the user moved far enough along the X axis
1429 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001430 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001431 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001432 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001433 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001434 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1435 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001436 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001437 }
1438 }
1439
Adam Cohen7d30a372013-07-01 17:03:59 -07001440 protected float getMaxScrollProgress() {
1441 return 1.0f;
1442 }
1443
Adam Cohenf8d28232011-02-01 21:47:00 -08001444 protected void cancelCurrentPageLongPress() {
1445 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001446 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001447 // Try canceling the long press. It could also have been scheduled
1448 // by a distant descendant, so use the mAllowLongPress flag to block
1449 // everything
1450 final View currentPage = getPageAt(mCurrentPage);
1451 if (currentPage != null) {
1452 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001453 }
1454 }
1455 }
1456
Adam Cohen7d30a372013-07-01 17:03:59 -07001457 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1458 final int halfScreenSize = getViewportWidth() / 2;
1459
1460 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1461 screenCenter = Math.max(halfScreenSize, screenCenter);
1462
1463 return getScrollProgress(screenCenter, v, page);
1464 }
1465
Adam Cohenb5ba0972011-09-07 18:02:31 -07001466 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001467 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001468
Adam Cohen96d30a12013-07-16 18:13:21 -07001469 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001470 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001471
1472 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001473 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1474 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001475 return scrollProgress;
1476 }
1477
Adam Cohenedb40762013-07-18 16:45:45 -07001478 public int getScrollForPage(int index) {
1479 if (mPageScrolls == null || index >= mPageScrolls.length) {
1480 return 0;
1481 } else {
1482 return mPageScrolls[index];
1483 }
1484 }
1485
Adam Cohene0f66b52010-11-23 15:06:07 -08001486 // This curve determines how the effect of scrolling over the limits of the page dimishes
1487 // as the user pulls further and further from the bounds
1488 private float overScrollInfluenceCurve(float f) {
1489 f -= 1.0f;
1490 return f * f * f + 1.0f;
1491 }
1492
Adam Cohenb5ba0972011-09-07 18:02:31 -07001493 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001494 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001495
1496 // We want to reach the max over scroll effect when the user has
1497 // over scrolled half the size of the screen
1498 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1499
1500 if (f == 0) return;
1501
1502 // Clamp this factor, f, to -1 < f < 1
1503 if (Math.abs(f) >= 1) {
1504 f /= Math.abs(f);
1505 }
1506
1507 int overScrollAmount = (int) Math.round(f * screenSize);
1508 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001509 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001510 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001511 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001512 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001513 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001514 }
1515 invalidate();
1516 }
1517
1518 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001519 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001520
1521 float f = (amount / screenSize);
1522
1523 if (f == 0) return;
1524 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1525
Adam Cohen7bfc9792011-01-28 13:52:37 -08001526 // Clamp this factor, f, to -1 < f < 1
1527 if (Math.abs(f) >= 1) {
1528 f /= Math.abs(f);
1529 }
1530
Adam Cohene0f66b52010-11-23 15:06:07 -08001531 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001532 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001533 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001534 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001535 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001536 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001537 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001538 }
1539 invalidate();
1540 }
1541
Adam Cohenb5ba0972011-09-07 18:02:31 -07001542 protected void overScroll(float amount) {
1543 dampedOverScroll(amount);
1544 }
1545
Michael Jurkac5b262c2011-01-12 20:24:50 -08001546 protected float maxOverScroll() {
1547 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001548 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001549 float f = 1.0f;
1550 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1551 return OVERSCROLL_DAMP_FACTOR * f;
1552 }
1553
Adam Cohenf358a4b2013-07-23 16:47:31 -07001554 protected void enableFreeScroll() {
1555 setEnableFreeScroll(true, -1);
1556 }
1557
1558 protected void disableFreeScroll(int snapPage) {
1559 setEnableFreeScroll(false, snapPage);
1560 }
1561
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001562 void updateFreescrollBounds() {
1563 getOverviewModePages(mTempVisiblePagesRange);
1564 if (isLayoutRtl()) {
1565 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1566 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1567 } else {
1568 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1569 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1570 }
1571 }
1572
Adam Cohenf358a4b2013-07-23 16:47:31 -07001573 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1574 mFreeScroll = freeScroll;
1575
1576 if (snapPage == -1) {
1577 snapPage = getPageNearestToCenterOfScreen();
1578 }
1579
Adam Cohenf358a4b2013-07-23 16:47:31 -07001580 if (!mFreeScroll) {
1581 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001582 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001583 updateFreescrollBounds();
1584 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001585 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1586 setCurrentPage(mTempVisiblePagesRange[0]);
1587 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1588 setCurrentPage(mTempVisiblePagesRange[1]);
1589 }
1590 }
1591
1592 setEnableOverscroll(!freeScroll);
1593 }
1594
1595 private void setEnableOverscroll(boolean enable) {
1596 mAllowOverScroll = enable;
1597 }
1598
1599 int getNearestHoverOverPageIndex() {
1600 if (mDragView != null) {
1601 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1602 + mDragView.getTranslationX());
1603 getOverviewModePages(mTempVisiblePagesRange);
1604 int minDistance = Integer.MAX_VALUE;
1605 int minIndex = indexOfChild(mDragView);
1606 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1607 View page = getPageAt(i);
1608 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1609 int d = Math.abs(dragX - pageX);
1610 if (d < minDistance) {
1611 minIndex = i;
1612 minDistance = d;
1613 }
1614 }
1615 return minIndex;
1616 }
1617 return -1;
1618 }
1619
Winson Chung321e9ee2010-08-09 13:37:56 -07001620 @Override
1621 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001622 if (DISABLE_TOUCH_INTERACTION) {
1623 return false;
1624 }
1625
Adam Cohen1697b792013-09-17 19:08:21 -07001626 super.onTouchEvent(ev);
1627
Winson Chung45e1d6e2010-11-09 17:19:49 -08001628 // Skip touch handling if there are no pages to swipe
1629 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1630
Michael Jurkab8f06722010-10-10 15:58:46 -07001631 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001632
1633 final int action = ev.getAction();
1634
1635 switch (action & MotionEvent.ACTION_MASK) {
1636 case MotionEvent.ACTION_DOWN:
1637 /*
1638 * If being flinged and user touches, stop the fling. isFinished
1639 * will be false if being flinged.
1640 */
1641 if (!mScroller.isFinished()) {
1642 mScroller.abortAnimation();
1643 }
1644
1645 // Remember where the motion event started
1646 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001647 mDownMotionY = mLastMotionY = ev.getY();
1648 mDownScrollX = getScrollX();
1649 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1650 mParentDownMotionX = p[0];
1651 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001652 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001653 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001654 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001655
Michael Jurka0142d492010-08-25 17:46:15 -07001656 if (mTouchState == TOUCH_STATE_SCROLLING) {
1657 pageBeginMoving();
1658 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001659 break;
1660
1661 case MotionEvent.ACTION_MOVE:
1662 if (mTouchState == TOUCH_STATE_SCROLLING) {
1663 // Scroll to follow the motion event
1664 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001665
1666 if (pointerIndex == -1) return true;
1667
Winson Chung321e9ee2010-08-09 13:37:56 -07001668 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001669 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001670
Adam Cohenaefd4e12011-02-14 16:39:38 -08001671 mTotalMotionX += Math.abs(deltaX);
1672
Winson Chungc0844aa2011-02-02 15:25:58 -08001673 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1674 // keep the remainder because we are actually testing if we've moved from the last
1675 // scrolled position (which is discrete).
1676 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001677 mTouchX += deltaX;
1678 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1679 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001680 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001681 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001682 } else {
1683 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001684 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001685 mLastMotionX = x;
1686 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001687 } else {
1688 awakenScrollBars();
1689 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001690 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1691 // Update the last motion position
1692 mLastMotionX = ev.getX();
1693 mLastMotionY = ev.getY();
1694
1695 // Update the parent down so that our zoom animations take this new movement into
1696 // account
1697 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1698 mParentDownMotionX = pt[0];
1699 mParentDownMotionY = pt[1];
1700 updateDragViewTranslationDuringDrag();
1701
1702 // Find the closest page to the touch point
1703 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001704
1705 // Change the drag view if we are hovering over the drop target
1706 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1707 (int) mParentDownMotionX, (int) mParentDownMotionY);
1708 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1709
Adam Cohen7d30a372013-07-01 17:03:59 -07001710 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1711 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1712 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1713 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1714
Adam Cohenf358a4b2013-07-23 16:47:31 -07001715 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1716 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1717 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001718 mTempVisiblePagesRange[0] = 0;
1719 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001720 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001721 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1722 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1723 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1724 mSidePageHoverIndex = pageUnderPointIndex;
1725 mSidePageHoverRunnable = new Runnable() {
1726 @Override
1727 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001728 // Setup the scroll to the correct page before we swap the views
1729 snapToPage(pageUnderPointIndex);
1730
1731 // For each of the pages between the paged view and the drag view,
1732 // animate them from the previous position to the new position in
1733 // the layout (as a result of the drag view moving in the layout)
1734 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1735 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1736 dragViewIndex + 1 : pageUnderPointIndex;
1737 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1738 dragViewIndex - 1 : pageUnderPointIndex;
1739 for (int i = lowerIndex; i <= upperIndex; ++i) {
1740 View v = getChildAt(i);
1741 // dragViewIndex < pageUnderPointIndex, so after we remove the
1742 // drag view all subsequent views to pageUnderPointIndex will
1743 // shift down.
1744 int oldX = getViewportOffsetX() + getChildOffset(i);
1745 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1746
1747 // Animate the view translation from its old position to its new
1748 // position
1749 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1750 if (anim != null) {
1751 anim.cancel();
1752 }
1753
1754 v.setTranslationX(oldX - newX);
1755 anim = new AnimatorSet();
1756 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1757 anim.playTogether(
1758 ObjectAnimator.ofFloat(v, "translationX", 0f));
1759 anim.start();
1760 v.setTag(anim);
1761 }
1762
1763 removeView(mDragView);
1764 onRemoveView(mDragView, false);
1765 addView(mDragView, pageUnderPointIndex);
1766 onAddView(mDragView, pageUnderPointIndex);
1767 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001768 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001769 }
1770 };
1771 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1772 }
1773 } else {
1774 removeCallbacks(mSidePageHoverRunnable);
1775 mSidePageHoverIndex = -1;
1776 }
Adam Cohen564976a2010-10-13 18:52:07 -07001777 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001778 determineScrollingStart(ev);
1779 }
1780 break;
1781
1782 case MotionEvent.ACTION_UP:
1783 if (mTouchState == TOUCH_STATE_SCROLLING) {
1784 final int activePointerId = mActivePointerId;
1785 final int pointerIndex = ev.findPointerIndex(activePointerId);
1786 final float x = ev.getX(pointerIndex);
1787 final VelocityTracker velocityTracker = mVelocityTracker;
1788 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1789 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001790 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001791 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001792 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1793 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001794
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001795 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1796
Adam Cohen00481b32011-11-18 12:03:48 -08001797 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001798 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001799
Adam Cohenf358a4b2013-07-23 16:47:31 -07001800 if (!mFreeScroll) {
1801 // In the case that the page is moved far to one direction and then is flung
1802 // in the opposite direction, we use a threshold to determine whether we should
1803 // just return to the starting page, or if we should skip one further.
1804 boolean returnToOriginalPage = false;
1805 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1806 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1807 returnToOriginalPage = true;
1808 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001809
Adam Cohenf358a4b2013-07-23 16:47:31 -07001810 int finalPage;
1811 // We give flings precedence over large moves, which is why we short-circuit our
1812 // test for a large move if a fling has been registered. That is, a large
1813 // move to the left and fling to the right will register as a fling to the right.
1814 final boolean isRtl = isLayoutRtl();
1815 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1816 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1817 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1818 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1819 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1820 snapToPageWithVelocity(finalPage, velocityX);
1821 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1822 (isFling && isVelocityXLeft)) &&
1823 mCurrentPage < getChildCount() - 1) {
1824 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1825 snapToPageWithVelocity(finalPage, velocityX);
1826 } else {
1827 snapToDestination();
1828 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1829 // at this point we have not moved beyond the touch slop
1830 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1831 // we can just page
1832 int nextPage = Math.max(0, mCurrentPage - 1);
1833 if (nextPage != mCurrentPage) {
1834 snapToPage(nextPage);
1835 } else {
1836 snapToDestination();
1837 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001838 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001839 if (!mScroller.isFinished()) {
1840 mScroller.abortAnimation();
1841 }
1842
1843 float scaleX = getScaleX();
1844 int vX = (int) (-velocityX * scaleX);
1845 int initialScrollX = (int) (getScrollX() * scaleX);
1846
1847 mScroller.fling(initialScrollX,
1848 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1849 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001850 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001851 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001852 // at this point we have not moved beyond the touch slop
1853 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1854 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001855 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1856 if (nextPage != mCurrentPage) {
1857 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001858 } else {
1859 snapToDestination();
1860 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001861 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1862 // Update the last motion position
1863 mLastMotionX = ev.getX();
1864 mLastMotionY = ev.getY();
1865
1866 // Update the parent down so that our zoom animations take this new movement into
1867 // account
1868 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1869 mParentDownMotionX = pt[0];
1870 mParentDownMotionY = pt[1];
1871 updateDragViewTranslationDuringDrag();
1872 boolean handledFling = false;
1873 if (!DISABLE_FLING_TO_DELETE) {
1874 // Check the velocity and see if we are flinging-to-delete
1875 PointF flingToDeleteVector = isFlingingToDelete();
1876 if (flingToDeleteVector != null) {
1877 onFlingToDelete(flingToDeleteVector);
1878 handledFling = true;
1879 }
1880 }
1881 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1882 (int) mParentDownMotionY)) {
1883 onDropToDelete();
1884 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001885 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001886 if (!mCancelTap) {
1887 onUnhandledTap(ev);
1888 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001889 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001890
1891 // Remove the callback to wait for the side page hover timeout
1892 removeCallbacks(mSidePageHoverRunnable);
1893 // End any intermediate reordering states
1894 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001895 break;
1896
1897 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001898 if (mTouchState == TOUCH_STATE_SCROLLING) {
1899 snapToDestination();
1900 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001901 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001902 break;
1903
1904 case MotionEvent.ACTION_POINTER_UP:
1905 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001906 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001907 break;
1908 }
1909
1910 return true;
1911 }
1912
Adam Cohen7d30a372013-07-01 17:03:59 -07001913 public void onFlingToDelete(View v) {}
1914 public void onRemoveView(View v, boolean deletePermanently) {}
1915 public void onRemoveViewAnimationCompleted() {}
1916 public void onAddView(View v, int index) {}
1917
1918 private void resetTouchState() {
1919 releaseVelocityTracker();
1920 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001921 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001922 mTouchState = TOUCH_STATE_REST;
1923 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001924 }
1925
Adam Cohen1697b792013-09-17 19:08:21 -07001926 protected void onUnhandledTap(MotionEvent ev) {
1927 ((Launcher) getContext()).onClick(this);
1928 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001929
Winson Chung185d7162011-02-28 13:47:29 -08001930 @Override
1931 public boolean onGenericMotionEvent(MotionEvent event) {
1932 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1933 switch (event.getAction()) {
1934 case MotionEvent.ACTION_SCROLL: {
1935 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1936 final float vscroll;
1937 final float hscroll;
1938 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1939 vscroll = 0;
1940 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1941 } else {
1942 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1943 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1944 }
1945 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001946 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1947 : (hscroll > 0 || vscroll > 0);
1948 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001949 scrollRight();
1950 } else {
1951 scrollLeft();
1952 }
1953 return true;
1954 }
1955 }
1956 }
1957 }
1958 return super.onGenericMotionEvent(event);
1959 }
1960
Michael Jurkab8f06722010-10-10 15:58:46 -07001961 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1962 if (mVelocityTracker == null) {
1963 mVelocityTracker = VelocityTracker.obtain();
1964 }
1965 mVelocityTracker.addMovement(ev);
1966 }
1967
1968 private void releaseVelocityTracker() {
1969 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001970 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001971 mVelocityTracker.recycle();
1972 mVelocityTracker = null;
1973 }
1974 }
1975
Winson Chung321e9ee2010-08-09 13:37:56 -07001976 private void onSecondaryPointerUp(MotionEvent ev) {
1977 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1978 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1979 final int pointerId = ev.getPointerId(pointerIndex);
1980 if (pointerId == mActivePointerId) {
1981 // This was our active pointer going up. Choose a new
1982 // active pointer and adjust accordingly.
1983 // TODO: Make this decision more intelligent.
1984 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1985 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1986 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001987 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001988 mActivePointerId = ev.getPointerId(newPointerIndex);
1989 if (mVelocityTracker != null) {
1990 mVelocityTracker.clear();
1991 }
1992 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001993 }
1994
Winson Chung321e9ee2010-08-09 13:37:56 -07001995 @Override
1996 public void requestChildFocus(View child, View focused) {
1997 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001998 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001999 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002000 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002001 }
2002 }
2003
Winson Chung1908d072011-02-24 18:09:44 -08002004 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002005 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002006 }
2007
Adam Cohen7d30a372013-07-01 17:03:59 -07002008 int getPageNearestToPoint(float x) {
2009 int index = 0;
2010 for (int i = 0; i < getChildCount(); ++i) {
2011 if (x < getChildAt(i).getRight() - getScrollX()) {
2012 return index;
2013 } else {
2014 index++;
2015 }
2016 }
2017 return Math.min(index, getChildCount() - 1);
2018 }
2019
Adam Cohend19d3ca2010-09-15 14:43:42 -07002020 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002021 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002022 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002023 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002024 final int childCount = getChildCount();
2025 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002026 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002027 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002028 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002029 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002030 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2031 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2032 minDistanceFromScreenCenter = distanceFromScreenCenter;
2033 minDistanceFromScreenCenterIndex = i;
2034 }
2035 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002036 return minDistanceFromScreenCenterIndex;
2037 }
2038
2039 protected void snapToDestination() {
2040 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002041 }
2042
Adam Cohene0f66b52010-11-23 15:06:07 -08002043 private static class ScrollInterpolator implements Interpolator {
2044 public ScrollInterpolator() {
2045 }
2046
2047 public float getInterpolation(float t) {
2048 t -= 1.0f;
2049 return t*t*t*t*t + 1;
2050 }
2051 }
2052
2053 // We want the duration of the page snap animation to be influenced by the distance that
2054 // the screen has to travel, however, we don't want this duration to be effected in a
2055 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2056 // of travel has on the overall snap duration.
2057 float distanceInfluenceForSnapDuration(float f) {
2058 f -= 0.5f; // center the values about 0.
2059 f *= 0.3f * Math.PI / 2.0f;
2060 return (float) Math.sin(f);
2061 }
2062
Michael Jurka0142d492010-08-25 17:46:15 -07002063 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002064 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002065 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002066
Adam Cohenedb40762013-07-18 16:45:45 -07002067 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002068 int delta = newX - mUnboundedScrollX;
2069 int duration = 0;
2070
Adam Cohen265b9a62011-12-07 14:37:18 -08002071 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002072 // If the velocity is low enough, then treat this more as an automatic page advance
2073 // as opposed to an apparent physical response to flinging
2074 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2075 return;
2076 }
2077
2078 // Here we compute a "distance" that will be used in the computation of the overall
2079 // snap duration. This is a function of the actual distance that needs to be traveled;
2080 // we keep this value close to half screen size in order to reduce the variance in snap
2081 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002082 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002083 float distance = halfScreenSize + halfScreenSize *
2084 distanceInfluenceForSnapDuration(distanceRatio);
2085
2086 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002087 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002088
2089 // we want the page's snap velocity to approximately match the velocity at which the
2090 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002091 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2092 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002093
2094 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002095 }
2096
2097 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002098 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002099 }
2100
Adam Cohen7d30a372013-07-01 17:03:59 -07002101 protected void snapToPageImmediately(int whichPage) {
2102 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2103 }
2104
Michael Jurka0142d492010-08-25 17:46:15 -07002105 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002106 snapToPage(whichPage, duration, false);
2107 }
2108
2109 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002110 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002111
Adam Cohenedb40762013-07-18 16:45:45 -07002112 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002113 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002114 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002115 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002116 }
2117
2118 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002119 snapToPage(whichPage, delta, duration, false);
2120 }
Michael Jurka0142d492010-08-25 17:46:15 -07002121
Adam Cohen7d30a372013-07-01 17:03:59 -07002122 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2123 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002124 View focusedChild = getFocusedChild();
2125 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002126 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002127 focusedChild.clearFocus();
2128 }
2129
2130 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002131 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002132 if (immediate) {
2133 duration = 0;
2134 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002135 duration = Math.abs(delta);
2136 }
2137
Adam Cohenf358a4b2013-07-23 16:47:31 -07002138 if (!mScroller.isFinished()) {
2139 mScroller.abortAnimation();
2140 }
Adam Cohen68d73932010-11-15 10:50:58 -08002141 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002142
Michael Jurka0142d492010-08-25 17:46:15 -07002143 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002144
2145 // Trigger a compute() to finish switching pages if necessary
2146 if (immediate) {
2147 computeScroll();
2148 }
2149
Winson Chung9c0565f2013-07-19 13:49:06 -07002150 // Defer loading associated pages until the scroll settles
2151 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2152
Adam Cohen7d30a372013-07-01 17:03:59 -07002153 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002154 invalidate();
2155 }
2156
Winson Chung321e9ee2010-08-09 13:37:56 -07002157 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002158 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002159 }
2160
2161 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002162 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002163 }
2164
Winson Chung86f77532010-08-24 11:08:22 -07002165 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002166 int result = -1;
2167 if (v != null) {
2168 ViewParent vp = v.getParent();
2169 int count = getChildCount();
2170 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002171 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002172 return i;
2173 }
2174 }
2175 }
2176 return result;
2177 }
2178
2179 /**
2180 * @return True is long presses are still allowed for the current touch
2181 */
2182 public boolean allowLongPress() {
2183 return mAllowLongPress;
2184 }
2185
Adam Cohendbdff6b2013-09-18 19:09:15 -07002186 @Override
2187 public boolean performLongClick() {
2188 mCancelTap = true;
2189 return super.performLongClick();
2190 }
2191
Michael Jurka0142d492010-08-25 17:46:15 -07002192 /**
2193 * Set true to allow long-press events to be triggered, usually checked by
2194 * {@link Launcher} to accept or block dpad-initiated long-presses.
2195 */
2196 public void setAllowLongPress(boolean allowLongPress) {
2197 mAllowLongPress = allowLongPress;
2198 }
2199
Winson Chung321e9ee2010-08-09 13:37:56 -07002200 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002201 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002202
2203 SavedState(Parcelable superState) {
2204 super(superState);
2205 }
2206
2207 private SavedState(Parcel in) {
2208 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002209 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002210 }
2211
2212 @Override
2213 public void writeToParcel(Parcel out, int flags) {
2214 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002215 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002216 }
2217
2218 public static final Parcelable.Creator<SavedState> CREATOR =
2219 new Parcelable.Creator<SavedState>() {
2220 public SavedState createFromParcel(Parcel in) {
2221 return new SavedState(in);
2222 }
2223
2224 public SavedState[] newArray(int size) {
2225 return new SavedState[size];
2226 }
2227 };
2228 }
2229
Winson Chungf314b0e2011-08-16 11:54:27 -07002230 protected void loadAssociatedPages(int page) {
2231 loadAssociatedPages(page, false);
2232 }
2233 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002234 if (mContentIsRefreshable) {
2235 final int count = getChildCount();
2236 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002237 int lowerPageBound = getAssociatedLowerPageBound(page);
2238 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002239 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2240 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002241 // First, clear any pages that should no longer be loaded
2242 for (int i = 0; i < count; ++i) {
2243 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002244 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002245 if (layout.getPageChildCount() > 0) {
2246 layout.removeAllViewsOnPage();
2247 }
2248 mDirtyPageContent.set(i, true);
2249 }
2250 }
2251 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002252 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002253 if ((i != page) && immediateAndOnly) {
2254 continue;
2255 }
Michael Jurka0142d492010-08-25 17:46:15 -07002256 if (lowerPageBound <= i && i <= upperPageBound) {
2257 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002258 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002259 mDirtyPageContent.set(i, false);
2260 }
Winson Chung86f77532010-08-24 11:08:22 -07002261 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002262 }
2263 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002264 }
2265 }
2266
Winson Chunge3193b92010-09-10 11:44:42 -07002267 protected int getAssociatedLowerPageBound(int page) {
2268 return Math.max(0, page - 1);
2269 }
2270 protected int getAssociatedUpperPageBound(int page) {
2271 final int count = getChildCount();
2272 return Math.min(page + 1, count - 1);
2273 }
2274
Winson Chung86f77532010-08-24 11:08:22 -07002275 /**
2276 * This method is called ONLY to synchronize the number of pages that the paged view has.
2277 * To actually fill the pages with information, implement syncPageItems() below. It is
2278 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2279 * and therefore, individual page items do not need to be updated in this method.
2280 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002281 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002282
2283 /**
2284 * This method is called to synchronize the items that are on a particular page. If views on
2285 * the page can be reused, then they should be updated within this method.
2286 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002287 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002288
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002289 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002290 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002291 }
2292 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002293 invalidatePageData(currentPage, false);
2294 }
2295 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002296 if (!mIsDataReady) {
2297 return;
2298 }
2299
Michael Jurka0142d492010-08-25 17:46:15 -07002300 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002301 // Force all scrolling-related behavior to end
2302 mScroller.forceFinished(true);
2303 mNextPage = INVALID_PAGE;
2304
Michael Jurka0142d492010-08-25 17:46:15 -07002305 // Update all the pages
2306 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002307
Winson Chung5a808352011-06-27 19:08:49 -07002308 // We must force a measure after we've loaded the pages to update the content width and
2309 // to determine the full scroll width
2310 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2311 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2312
2313 // Set a new page as the current page if necessary
2314 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002315 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002316 }
2317
Michael Jurka0142d492010-08-25 17:46:15 -07002318 // Mark each of the pages as dirty
2319 final int count = getChildCount();
2320 mDirtyPageContent.clear();
2321 for (int i = 0; i < count; ++i) {
2322 mDirtyPageContent.add(true);
2323 }
2324
2325 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002326 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002327 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002328 }
Adam Cohen06559042013-09-29 18:30:56 -07002329 if (isPageMoving()) {
2330 // If the page is moving, then snap it to the final position to ensure we don't get
2331 // stuck between pages
2332 snapToDestination();
2333 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002334 }
Winson Chung007c6982011-06-14 13:27:53 -07002335
Adam Cohen7d30a372013-07-01 17:03:59 -07002336 // Animate the drag view back to the original position
2337 void animateDragViewToOriginalPosition() {
2338 if (mDragView != null) {
2339 AnimatorSet anim = new AnimatorSet();
2340 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2341 anim.playTogether(
2342 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002343 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2344 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2345 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002346 anim.addListener(new AnimatorListenerAdapter() {
2347 @Override
2348 public void onAnimationEnd(Animator animation) {
2349 onPostReorderingAnimationCompleted();
2350 }
2351 });
2352 anim.start();
2353 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002354 }
2355
Adam Cohen7d30a372013-07-01 17:03:59 -07002356 protected void onStartReordering() {
2357 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2358 mTouchState = TOUCH_STATE_REORDERING;
2359 mIsReordering = true;
2360
Adam Cohen7d30a372013-07-01 17:03:59 -07002361 // We must invalidate to trigger a redraw to update the layers such that the drag view
2362 // is always drawn on top
2363 invalidate();
2364 }
2365
2366 private void onPostReorderingAnimationCompleted() {
2367 // Trigger the callback when reordering has settled
2368 --mPostReorderingPreZoomInRemainingAnimationCount;
2369 if (mPostReorderingPreZoomInRunnable != null &&
2370 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2371 mPostReorderingPreZoomInRunnable.run();
2372 mPostReorderingPreZoomInRunnable = null;
2373 }
2374 }
2375
2376 protected void onEndReordering() {
2377 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002378 }
2379
Adam Cohenf358a4b2013-07-23 16:47:31 -07002380 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002381 int dragViewIndex = indexOfChild(v);
2382
2383 if (mTouchState != TOUCH_STATE_REST) return false;
2384
Adam Cohen7d30a372013-07-01 17:03:59 -07002385 mTempVisiblePagesRange[0] = 0;
2386 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002387 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002388 mReorderingStarted = true;
2389
2390 // Check if we are within the reordering range
2391 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002392 dragViewIndex <= mTempVisiblePagesRange[1]) {
2393 // Find the drag view under the pointer
2394 mDragView = getChildAt(dragViewIndex);
2395 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2396 mDragViewBaselineLeft = mDragView.getLeft();
2397 disableFreeScroll(-1);
2398 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002399 return true;
2400 }
2401 return false;
2402 }
2403
2404 boolean isReordering(boolean testTouchState) {
2405 boolean state = mIsReordering;
2406 if (testTouchState) {
2407 state &= (mTouchState == TOUCH_STATE_REORDERING);
2408 }
2409 return state;
2410 }
2411 void endReordering() {
2412 // For simplicity, we call endReordering sometimes even if reordering was never started.
2413 // In that case, we don't want to do anything.
2414 if (!mReorderingStarted) return;
2415 mReorderingStarted = false;
2416
2417 // If we haven't flung-to-delete the current child, then we just animate the drag view
2418 // back into position
2419 final Runnable onCompleteRunnable = new Runnable() {
2420 @Override
2421 public void run() {
2422 onEndReordering();
2423 }
2424 };
2425 if (!mDeferringForDelete) {
2426 mPostReorderingPreZoomInRunnable = new Runnable() {
2427 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002428 onCompleteRunnable.run();
2429 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002430 };
2431 };
2432
2433 mPostReorderingPreZoomInRemainingAnimationCount =
2434 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2435 // Snap to the current page
2436 snapToPage(indexOfChild(mDragView), 0);
2437 // Animate the drag view back to the front position
2438 animateDragViewToOriginalPosition();
2439 } else {
2440 // Handled in post-delete-animation-callbacks
2441 }
2442 }
2443
Adam Cohen7d30a372013-07-01 17:03:59 -07002444 /*
2445 * Flinging to delete - IN PROGRESS
2446 */
2447 private PointF isFlingingToDelete() {
2448 ViewConfiguration config = ViewConfiguration.get(getContext());
2449 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2450
2451 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2452 // Do a quick dot product test to ensure that we are flinging upwards
2453 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2454 mVelocityTracker.getYVelocity());
2455 PointF upVec = new PointF(0f, -1f);
2456 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2457 (vel.length() * upVec.length()));
2458 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2459 return vel;
2460 }
2461 }
2462 return null;
2463 }
2464
2465 /**
2466 * Creates an animation from the current drag view along its current velocity vector.
2467 * For this animation, the alpha runs for a fixed duration and we update the position
2468 * progressively.
2469 */
2470 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2471 private View mDragView;
2472 private PointF mVelocity;
2473 private Rect mFrom;
2474 private long mPrevTime;
2475 private float mFriction;
2476
2477 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2478
2479 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2480 long startTime, float friction) {
2481 mDragView = dragView;
2482 mVelocity = vel;
2483 mFrom = from;
2484 mPrevTime = startTime;
2485 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2486 }
2487
2488 @Override
2489 public void onAnimationUpdate(ValueAnimator animation) {
2490 float t = ((Float) animation.getAnimatedValue()).floatValue();
2491 long curTime = AnimationUtils.currentAnimationTimeMillis();
2492
2493 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2494 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2495
2496 mDragView.setTranslationX(mFrom.left);
2497 mDragView.setTranslationY(mFrom.top);
2498 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2499
2500 mVelocity.x *= mFriction;
2501 mVelocity.y *= mFriction;
2502 mPrevTime = curTime;
2503 }
2504 };
2505
2506 private static final int ANIM_TAG_KEY = 100;
2507
2508 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2509 return new Runnable() {
2510 @Override
2511 public void run() {
2512 int dragViewIndex = indexOfChild(dragView);
2513
2514 // For each of the pages around the drag view, animate them from the previous
2515 // position to the new position in the layout (as a result of the drag view moving
2516 // in the layout)
2517 // NOTE: We can make an assumption here because we have side-bound pages that we
2518 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002519 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002520 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2521 boolean slideFromLeft = (isLastWidgetPage ||
2522 dragViewIndex > mTempVisiblePagesRange[0]);
2523
2524 // Setup the scroll to the correct page before we swap the views
2525 if (slideFromLeft) {
2526 snapToPageImmediately(dragViewIndex - 1);
2527 }
2528
2529 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2530 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2531 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2532 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2533 ArrayList<Animator> animations = new ArrayList<Animator>();
2534 for (int i = lowerIndex; i <= upperIndex; ++i) {
2535 View v = getChildAt(i);
2536 // dragViewIndex < pageUnderPointIndex, so after we remove the
2537 // drag view all subsequent views to pageUnderPointIndex will
2538 // shift down.
2539 int oldX = 0;
2540 int newX = 0;
2541 if (slideFromLeft) {
2542 if (i == 0) {
2543 // Simulate the page being offscreen with the page spacing
2544 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2545 - mPageSpacing;
2546 } else {
2547 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2548 }
2549 newX = getViewportOffsetX() + getChildOffset(i);
2550 } else {
2551 oldX = getChildOffset(i) - getChildOffset(i - 1);
2552 newX = 0;
2553 }
2554
2555 // Animate the view translation from its old position to its new
2556 // position
2557 AnimatorSet anim = (AnimatorSet) v.getTag();
2558 if (anim != null) {
2559 anim.cancel();
2560 }
2561
2562 // Note: Hacky, but we want to skip any optimizations to not draw completely
2563 // hidden views
2564 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2565 v.setTranslationX(oldX - newX);
2566 anim = new AnimatorSet();
2567 anim.playTogether(
2568 ObjectAnimator.ofFloat(v, "translationX", 0f),
2569 ObjectAnimator.ofFloat(v, "alpha", 1f));
2570 animations.add(anim);
2571 v.setTag(ANIM_TAG_KEY, anim);
2572 }
2573
2574 AnimatorSet slideAnimations = new AnimatorSet();
2575 slideAnimations.playTogether(animations);
2576 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2577 slideAnimations.addListener(new AnimatorListenerAdapter() {
2578 @Override
2579 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002580 mDeferringForDelete = false;
2581 onEndReordering();
2582 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002583 }
2584 });
2585 slideAnimations.start();
2586
2587 removeView(dragView);
2588 onRemoveView(dragView, true);
2589 }
2590 };
2591 }
2592
2593 public void onFlingToDelete(PointF vel) {
2594 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2595
2596 // NOTE: Because it takes time for the first frame of animation to actually be
2597 // called and we expect the animation to be a continuation of the fling, we have
2598 // to account for the time that has elapsed since the fling finished. And since
2599 // we don't have a startDelay, we will always get call to update when we call
2600 // start() (which we want to ignore).
2601 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2602 private int mCount = -1;
2603 private long mStartTime;
2604 private float mOffset;
2605 /* Anonymous inner class ctor */ {
2606 mStartTime = startTime;
2607 }
2608
2609 @Override
2610 public float getInterpolation(float t) {
2611 if (mCount < 0) {
2612 mCount++;
2613 } else if (mCount == 0) {
2614 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2615 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2616 mCount++;
2617 }
2618 return Math.min(1f, mOffset + t);
2619 }
2620 };
2621
2622 final Rect from = new Rect();
2623 final View dragView = mDragView;
2624 from.left = (int) dragView.getTranslationX();
2625 from.top = (int) dragView.getTranslationY();
2626 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2627 from, startTime, FLING_TO_DELETE_FRICTION);
2628
2629 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2630
2631 // Create and start the animation
2632 ValueAnimator mDropAnim = new ValueAnimator();
2633 mDropAnim.setInterpolator(tInterpolator);
2634 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2635 mDropAnim.setFloatValues(0f, 1f);
2636 mDropAnim.addUpdateListener(updateCb);
2637 mDropAnim.addListener(new AnimatorListenerAdapter() {
2638 public void onAnimationEnd(Animator animation) {
2639 onAnimationEndRunnable.run();
2640 }
2641 });
2642 mDropAnim.start();
2643 mDeferringForDelete = true;
2644 }
2645
2646 /* Drag to delete */
2647 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2648 if (mDeleteDropTarget != null) {
2649 mAltTmpRect.set(0, 0, 0, 0);
2650 View parent = (View) mDeleteDropTarget.getParent();
2651 if (parent != null) {
2652 parent.getGlobalVisibleRect(mAltTmpRect);
2653 }
2654 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2655 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2656 return mTmpRect.contains(x, y);
2657 }
2658 return false;
2659 }
2660
2661 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2662
2663 private void onDropToDelete() {
2664 final View dragView = mDragView;
2665
2666 final float toScale = 0f;
2667 final float toAlpha = 0f;
2668
2669 // Create and start the complex animation
2670 ArrayList<Animator> animations = new ArrayList<Animator>();
2671 AnimatorSet motionAnim = new AnimatorSet();
2672 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2673 motionAnim.playTogether(
2674 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2675 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2676 animations.add(motionAnim);
2677
2678 AnimatorSet alphaAnim = new AnimatorSet();
2679 alphaAnim.setInterpolator(new LinearInterpolator());
2680 alphaAnim.playTogether(
2681 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2682 animations.add(alphaAnim);
2683
2684 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2685
2686 AnimatorSet anim = new AnimatorSet();
2687 anim.playTogether(animations);
2688 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2689 anim.addListener(new AnimatorListenerAdapter() {
2690 public void onAnimationEnd(Animator animation) {
2691 onAnimationEndRunnable.run();
2692 }
2693 });
2694 anim.start();
2695
2696 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002697 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002698
2699 /* Accessibility */
2700 @Override
2701 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2702 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002703 info.setScrollable(getPageCount() > 1);
2704 if (getCurrentPage() < getPageCount() - 1) {
2705 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2706 }
2707 if (getCurrentPage() > 0) {
2708 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2709 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002710 }
2711
2712 @Override
2713 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2714 super.onInitializeAccessibilityEvent(event);
2715 event.setScrollable(true);
2716 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2717 event.setFromIndex(mCurrentPage);
2718 event.setToIndex(mCurrentPage);
2719 event.setItemCount(getChildCount());
2720 }
2721 }
2722
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002723 @Override
2724 public boolean performAccessibilityAction(int action, Bundle arguments) {
2725 if (super.performAccessibilityAction(action, arguments)) {
2726 return true;
2727 }
2728 switch (action) {
2729 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2730 if (getCurrentPage() < getPageCount() - 1) {
2731 scrollRight();
2732 return true;
2733 }
2734 } break;
2735 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2736 if (getCurrentPage() > 0) {
2737 scrollLeft();
2738 return true;
2739 }
2740 } break;
2741 }
2742 return false;
2743 }
2744
Adam Cohen0ffac432013-07-10 11:19:26 -07002745 protected String getCurrentPageDescription() {
2746 return String.format(getContext().getString(R.string.default_scroll_format),
2747 getNextPage() + 1, getChildCount());
2748 }
2749
Winson Chungd11265e2011-08-30 13:37:23 -07002750 @Override
2751 public boolean onHoverEvent(android.view.MotionEvent event) {
2752 return true;
2753 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002754}