blob: 3e2ec58575b286cfe62ee41ed40355e92e08fb55 [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;
Adam Cohen53805212013-10-01 10:39:23 -070035import android.support.v4.view.accessibility.AccessibilityEventCompat;
Winson Chung321e9ee2010-08-09 13:37:56 -070036import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070047import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070048import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070049import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070050import android.view.animation.AnimationUtils;
51import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080052import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070053import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070054import android.widget.Scroller;
55
Winson Chung6a0f57d2011-06-29 20:10:49 -070056import java.util.ArrayList;
57
Winson Chungc58497e2013-09-03 17:48:37 -070058interface Page {
59 public int getPageChildCount();
60 public View getChildOnPageAt(int i);
61 public void removeAllViewsOnPage();
62 public void removeViewOnPageAt(int i);
63 public int indexOfChildOnPage(View v);
64}
65
Winson Chung321e9ee2010-08-09 13:37:56 -070066/**
67 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070068 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070069 */
Michael Jurka8b805b12012-04-18 14:23:14 -070070public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070071 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070072 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070073 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070074
Winson Chung86f77532010-08-24 11:08:22 -070075 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070076 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070077
Adam Cohen7d30a372013-07-01 17:03:59 -070078 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070079 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070080 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070081
Adam Cohenb5ba0972011-09-07 18:02:31 -070082 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070083 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080084
Adam Cohenb64cb5a2011-02-15 13:53:42 -080085 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080086 // The page is moved more than halfway, automatically move to the next page on touch up.
87 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080088
Adam Cohen265b9a62011-12-07 14:37:18 -080089 // The following constants need to be scaled based on density. The scaled versions will be
90 // assigned to the corresponding member variables below.
91 private static final int FLING_THRESHOLD_VELOCITY = 500;
92 private static final int MIN_SNAP_VELOCITY = 1500;
93 private static final int MIN_FLING_VELOCITY = 250;
94
Adam Cohen7d30a372013-07-01 17:03:59 -070095 // We are disabling touch interaction of the widget region for factory ROM.
96 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070097 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070098 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070099
Adam Cohen21cd0022013-10-09 18:57:02 -0700100 public static final int INVALID_RESTORE_PAGE = -1001;
101
Adam Cohenf358a4b2013-07-23 16:47:31 -0700102 private boolean mFreeScroll = false;
103 private int mFreeScrollMinScrollX = -1;
104 private int mFreeScrollMaxScrollX = -1;
105
Winson Chung8aad6102012-05-11 16:27:49 -0700106 static final int AUTOMATIC_PAGE_SPACING = -1;
107
Adam Cohen265b9a62011-12-07 14:37:18 -0800108 protected int mFlingThresholdVelocity;
109 protected int mMinFlingVelocity;
110 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700111
Adam Cohenb5ba0972011-09-07 18:02:31 -0700112 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700113 protected float mSmoothingTime;
114 protected float mTouchX;
115
116 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700117 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700118
119 protected int mCurrentPage;
Adam Cohen21cd0022013-10-09 18:57:02 -0700120 protected int mRestorePage = INVALID_RESTORE_PAGE;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700121 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700122
Michael Jurka0142d492010-08-25 17:46:15 -0700123 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800124 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700125 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126 private VelocityTracker mVelocityTracker;
Adam Cohen3b185e22013-10-29 14:45:58 -0700127 private int mPageSpacing = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -0700128
Adam Cohen7d30a372013-07-01 17:03:59 -0700129 private float mParentDownMotionX;
130 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700131 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700132 private float mDownMotionY;
133 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700134 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800135 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800136 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800137 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800138 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700139 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700140
Adam Cohendbdff6b2013-09-18 19:09:15 -0700141 private boolean mCancelTap;
142
Adam Cohenedb40762013-07-18 16:45:45 -0700143 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700144
Michael Jurka0142d492010-08-25 17:46:15 -0700145 protected final static int TOUCH_STATE_REST = 0;
146 protected final static int TOUCH_STATE_SCROLLING = 1;
147 protected final static int TOUCH_STATE_PREV_PAGE = 2;
148 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700149 protected final static int TOUCH_STATE_REORDERING = 4;
150
Adam Cohene45440e2010-10-14 18:33:38 -0700151 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700152
Michael Jurka0142d492010-08-25 17:46:15 -0700153 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700154 protected boolean mForceScreenScrolled = false;
Adam Cohencae7f572013-11-04 14:42:52 -0800155 private boolean mScrollAbortedFromIntercept = false;
156
Winson Chung321e9ee2010-08-09 13:37:56 -0700157
Michael Jurka0142d492010-08-25 17:46:15 -0700158 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700159
Michael Jurka7426c422010-11-11 15:23:47 -0800160 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700161 private int mPagingTouchSlop;
162 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700163 protected int mPageLayoutPaddingTop;
164 protected int mPageLayoutPaddingBottom;
165 protected int mPageLayoutPaddingLeft;
166 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700167 protected int mPageLayoutWidthGap;
168 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700169 protected int mCellCountX = 0;
170 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700171 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800172 protected boolean mAllowOverScroll = true;
173 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800174 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700175 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700176
Michael Jurka8b805b12012-04-18 14:23:14 -0700177 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800178 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
179 // the screens from continuing to translate beyond the normal bounds.
180 protected int mOverScrollX;
181
Michael Jurka5f1c5092010-09-03 14:15:02 -0700182 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700183
Michael Jurka5f1c5092010-09-03 14:15:02 -0700184 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700185
Winson Chung86f77532010-08-24 11:08:22 -0700186 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700187
Michael Jurkae326f182011-11-21 14:05:46 -0800188 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700189
Michael Jurka0142d492010-08-25 17:46:15 -0700190 // If true, syncPages and syncPageItems will be called to refresh pages
191 protected boolean mContentIsRefreshable = true;
192
193 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700194 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700195
196 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
197 // to switch to a new page
198 protected boolean mUsePagingTouchSlop = true;
199
Michael Jurka8b805b12012-04-18 14:23:14 -0700200 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700201 // (SmoothPagedView does this)
202 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700203 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700204
Patrick Dubroy1262e362010-10-06 15:49:50 -0700205 protected boolean mIsPageMoving = false;
206
Winson Chungf0ea4d32011-06-06 14:27:16 -0700207 // All syncs and layout passes are deferred until data is ready.
208 protected boolean mIsDataReady = false;
209
Adam Cohen7d30a372013-07-01 17:03:59 -0700210 protected boolean mAllowLongPress = true;
211
Winson Chungd2be3812013-07-16 11:11:32 -0700212 // Page Indicator
213 private int mPageIndicatorViewId;
214 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700215 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700216
Adam Cohen7d30a372013-07-01 17:03:59 -0700217 // The viewport whether the pages are to be contained (the actual view may be larger than the
218 // viewport)
219 private Rect mViewport = new Rect();
220
221 // Reordering
222 // We use the min scale to determine how much to expand the actually PagedView measured
223 // dimensions such that when we are zoomed out, the view is not clipped
224 private int REORDERING_DROP_REPOSITION_DURATION = 200;
225 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
226 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700227 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700228 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700229 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700230 protected View mDragView;
231 protected AnimatorSet mZoomInOutAnim;
232 private Runnable mSidePageHoverRunnable;
233 private int mSidePageHoverIndex = -1;
234 // This variable's scope is only for the duration of startReordering() and endReordering()
235 private boolean mReorderingStarted = false;
236 // This variable's scope is for the duration of startReordering() and after the zoomIn()
237 // animation after endReordering()
238 private boolean mIsReordering;
239 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
240 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
241 private int mPostReorderingPreZoomInRemainingAnimationCount;
242 private Runnable mPostReorderingPreZoomInRunnable;
243
Adam Cohen7d30a372013-07-01 17:03:59 -0700244 // Convenience/caching
245 private Matrix mTmpInvMatrix = new Matrix();
246 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700247 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700248 private Rect mTmpRect = new Rect();
249 private Rect mAltTmpRect = new Rect();
250
251 // Fling to delete
252 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
253 private float FLING_TO_DELETE_FRICTION = 0.035f;
254 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
255 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
256 protected int mFlingToDeleteThresholdVelocity = -1400;
257 // Drag to delete
258 private boolean mDeferringForDelete = false;
259 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
260 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
261
262 // Drop to delete
263 private View mDeleteDropTarget;
264
Adam Cohen7d30a372013-07-01 17:03:59 -0700265 // Bouncer
266 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700267
John Spurlock77e1f472013-09-11 10:09:51 -0400268 protected final Rect mInsets = new Rect();
269
Winson Chung86f77532010-08-24 11:08:22 -0700270 public interface PageSwitchListener {
271 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700272 }
273
Winson Chung321e9ee2010-08-09 13:37:56 -0700274 public PagedView(Context context) {
275 this(context, null);
276 }
277
278 public PagedView(Context context, AttributeSet attrs) {
279 this(context, attrs, 0);
280 }
281
282 public PagedView(Context context, AttributeSet attrs, int defStyle) {
283 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700284
Adam Cohen9c4949e2010-10-05 12:27:22 -0700285 TypedArray a = context.obtainStyledAttributes(attrs,
286 R.styleable.PagedView, defStyle, 0);
Adam Cohen0cd0eba2013-10-28 14:22:25 -0700287
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800289 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700290 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800291 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800293 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700294 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800295 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700296 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700297 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700298 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700299 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700300 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700301 a.recycle();
302
Winson Chung321e9ee2010-08-09 13:37:56 -0700303 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700304 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700305 }
306
307 /**
308 * Initializes various states for this workspace.
309 */
Michael Jurka0142d492010-08-25 17:46:15 -0700310 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700311 mDirtyPageContent = new ArrayList<Boolean>();
312 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800313 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700314 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700315 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700316
317 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700318 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700319 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
320 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700321 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800322
Adam Cohen7d30a372013-07-01 17:03:59 -0700323 // Scale the fling-to-delete threshold by the density
324 mFlingToDeleteThresholdVelocity =
325 (int) (mFlingToDeleteThresholdVelocity * mDensity);
326
Adam Cohen265b9a62011-12-07 14:37:18 -0800327 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
328 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
329 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700330 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700331 }
332
Winson Chungd2be3812013-07-16 11:11:32 -0700333 protected void onAttachedToWindow() {
Adam Cohen53805212013-10-01 10:39:23 -0700334 super.onAttachedToWindow();
335
Winson Chungd2be3812013-07-16 11:11:32 -0700336 // Hook up the page indicator
337 ViewGroup parent = (ViewGroup) getParent();
338 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
339 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700340 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700341
Winson Chung7819a562013-09-19 15:55:45 -0700342 ArrayList<PageIndicator.PageMarkerResources> markers =
343 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700344 for (int i = 0; i < getChildCount(); ++i) {
345 markers.add(getPageIndicatorMarker(i));
346 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700347
Winson Chungc58497e2013-09-03 17:48:37 -0700348 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenfbdf4272013-10-09 13:02:21 -0700349
350 OnClickListener listener = getPageIndicatorClickListener();
351 if (listener != null) {
352 mPageIndicator.setOnClickListener(listener);
353 }
Adam Cohen53805212013-10-01 10:39:23 -0700354 mPageIndicator.setContentDescription(getPageIndicatorDescription());
Winson Chungd2be3812013-07-16 11:11:32 -0700355 }
356 }
357
Adam Cohen53805212013-10-01 10:39:23 -0700358 protected String getPageIndicatorDescription() {
359 return getCurrentPageDescription();
360 }
361
362 protected OnClickListener getPageIndicatorClickListener() {
363 return null;
364 }
365
Winson Chungd2be3812013-07-16 11:11:32 -0700366 protected void onDetachedFromWindow() {
367 // Unhook the page indicator
368 mPageIndicator = null;
369 }
370
Adam Cohen7d30a372013-07-01 17:03:59 -0700371 void setDeleteDropTarget(View v) {
372 mDeleteDropTarget = v;
373 }
374
375 // Convenience methods to map points from self to parent and vice versa
376 float[] mapPointFromViewToParent(View v, float x, float y) {
377 mTmpPoint[0] = x;
378 mTmpPoint[1] = y;
379 v.getMatrix().mapPoints(mTmpPoint);
380 mTmpPoint[0] += v.getLeft();
381 mTmpPoint[1] += v.getTop();
382 return mTmpPoint;
383 }
384 float[] mapPointFromParentToView(View v, float x, float y) {
385 mTmpPoint[0] = x - v.getLeft();
386 mTmpPoint[1] = y - v.getTop();
387 v.getMatrix().invert(mTmpInvMatrix);
388 mTmpInvMatrix.mapPoints(mTmpPoint);
389 return mTmpPoint;
390 }
391
392 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700393 if (mDragView != null) {
394 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
395 (mDragViewBaselineLeft - mDragView.getLeft());
396 float y = mLastMotionY - mDownMotionY;
397 mDragView.setTranslationX(x);
398 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700399
Adam Cohenf358a4b2013-07-23 16:47:31 -0700400 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
401 + x + ", " + y);
402 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700403 }
404
405 public void setMinScale(float f) {
406 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700407 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700408 requestLayout();
409 }
410
411 @Override
412 public void setScaleX(float scaleX) {
413 super.setScaleX(scaleX);
414 if (isReordering(true)) {
415 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
416 mLastMotionX = p[0];
417 mLastMotionY = p[1];
418 updateDragViewTranslationDuringDrag();
419 }
420 }
421
422 // Convenience methods to get the actual width/height of the PagedView (since it is measured
423 // to be larger to account for the minimum possible scale)
424 int getViewportWidth() {
425 return mViewport.width();
426 }
427 int getViewportHeight() {
428 return mViewport.height();
429 }
430
431 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
432 // PagedView both horizontally and vertically
433 int getViewportOffsetX() {
434 return (getMeasuredWidth() - getViewportWidth()) / 2;
435 }
436
437 int getViewportOffsetY() {
438 return (getMeasuredHeight() - getViewportHeight()) / 2;
439 }
440
Adam Cohenedb40762013-07-18 16:45:45 -0700441 PageIndicator getPageIndicator() {
442 return mPageIndicator;
443 }
Winson Chung7819a562013-09-19 15:55:45 -0700444 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
445 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700446 }
Adam Cohenedb40762013-07-18 16:45:45 -0700447
Winson Chung86f77532010-08-24 11:08:22 -0700448 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
449 mPageSwitchListener = pageSwitchListener;
450 if (mPageSwitchListener != null) {
451 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700452 }
453 }
454
455 /**
Winson Chung52aee602013-01-30 12:01:02 -0800456 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
457 */
458 public boolean isLayoutRtl() {
459 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
460 }
461
462 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700463 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
464 * out pages.
465 */
466 protected void setDataIsReady() {
467 mIsDataReady = true;
468 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700469
Winson Chungf0ea4d32011-06-06 14:27:16 -0700470 protected boolean isDataReady() {
471 return mIsDataReady;
472 }
473
474 /**
Winson Chung86f77532010-08-24 11:08:22 -0700475 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700476 *
Winson Chung86f77532010-08-24 11:08:22 -0700477 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700478 */
Winson Chung86f77532010-08-24 11:08:22 -0700479 int getCurrentPage() {
480 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700481 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700482
Winson Chung360e63f2012-04-27 13:48:05 -0700483 int getNextPage() {
484 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
485 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700486
Winson Chung86f77532010-08-24 11:08:22 -0700487 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700488 return getChildCount();
489 }
490
Winson Chung86f77532010-08-24 11:08:22 -0700491 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700492 return getChildAt(index);
493 }
494
Adam Cohenae4f1552011-10-20 00:15:42 -0700495 protected int indexToPage(int index) {
496 return index;
497 }
498
Winson Chung321e9ee2010-08-09 13:37:56 -0700499 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800500 * Updates the scroll of the current page immediately to its final scroll position. We use this
501 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
502 * the previous tab page.
503 */
504 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700505 // If the current page is invalid, just reset the scroll position to zero
506 int newX = 0;
507 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700508 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700509 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800510 scrollTo(newX, 0);
511 mScroller.setFinalX(newX);
Adam Cohen4fe4c932013-10-28 16:02:34 -0700512 forceFinishScroller();
Winson Chungbbc60d82010-11-11 16:34:41 -0800513 }
514
515 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700516 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
Adam Cohen4fe4c932013-10-28 16:02:34 -0700517 * {@link #updateCurrentPageScroll()} should be called, to correctly set the final state and
518 * re-enable scrolling.
Chet Haasebc2f0822012-10-26 17:59:53 -0700519 */
Adam Cohen4fe4c932013-10-28 16:02:34 -0700520 void stopScrolling() {
Winson Chungb88ae412013-10-29 17:21:56 -0700521 mCurrentPage = getNextPage();
Adam Cohen4fe4c932013-10-28 16:02:34 -0700522 forceFinishScroller();
Chet Haasebc2f0822012-10-26 17:59:53 -0700523 }
524
Adam Cohen8bdbaab2013-10-29 15:25:02 -0700525 private void abortScrollerAnimation(boolean resetNextPage) {
Adam Cohen4fe4c932013-10-28 16:02:34 -0700526 mScroller.abortAnimation();
527 // We need to clean up the next page here to avoid computeScrollHelper from
528 // updating current page on the pass.
Adam Cohen8bdbaab2013-10-29 15:25:02 -0700529 if (resetNextPage) {
530 mNextPage = INVALID_PAGE;
531 }
Chet Haasebc2f0822012-10-26 17:59:53 -0700532 }
Adam Cohen4fe4c932013-10-28 16:02:34 -0700533
534 private void forceFinishScroller() {
535 mScroller.forceFinished(true);
536 // We need to clean up the next page here to avoid computeScrollHelper from
537 // updating current page on the pass.
538 mNextPage = INVALID_PAGE;
539 }
540
Chet Haasebc2f0822012-10-26 17:59:53 -0700541 /**
Winson Chung86f77532010-08-24 11:08:22 -0700542 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700543 */
Winson Chung86f77532010-08-24 11:08:22 -0700544 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800545 if (!mScroller.isFinished()) {
Adam Cohen8bdbaab2013-10-29 15:25:02 -0700546 abortScrollerAnimation(true);
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800547 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800548 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
549 // the default
550 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800551 return;
552 }
Adam Cohene61a9a22013-06-11 15:45:31 -0700553 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700554 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700555 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700556 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800557 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700558 }
559
Winson Chung8c87cd82013-07-23 16:20:10 -0700560 /**
561 * The restore page will be set in place of the current page at the next (likely first)
562 * layout.
563 */
564 void setRestorePage(int restorePage) {
565 mRestorePage = restorePage;
566 }
567
Michael Jurka0142d492010-08-25 17:46:15 -0700568 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700569 if (mPageSwitchListener != null) {
570 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700571 }
Winson Chungd2be3812013-07-16 11:11:32 -0700572
573 // Update the page indicator (when we aren't reordering)
574 if (mPageIndicator != null && !isReordering(false)) {
575 mPageIndicator.setActiveMarker(getNextPage());
576 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700577 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800578 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700579 if (!mIsPageMoving) {
580 mIsPageMoving = true;
581 onPageBeginMoving();
582 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700583 }
584
Michael Jurkace7e05f2011-02-01 22:02:35 -0800585 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700586 if (mIsPageMoving) {
587 mIsPageMoving = false;
588 onPageEndMoving();
589 }
Michael Jurka0142d492010-08-25 17:46:15 -0700590 }
591
Adam Cohen26976d92011-03-22 15:33:33 -0700592 protected boolean isPageMoving() {
593 return mIsPageMoving;
594 }
595
Michael Jurka0142d492010-08-25 17:46:15 -0700596 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700597 protected void onPageBeginMoving() {
598 }
599
600 // a method that subclasses can override to add behavior
601 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700602 }
603
Winson Chung321e9ee2010-08-09 13:37:56 -0700604 /**
Winson Chung86f77532010-08-24 11:08:22 -0700605 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700606 *
607 * @param l The listener used to respond to long clicks.
608 */
609 @Override
610 public void setOnLongClickListener(OnLongClickListener l) {
611 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700612 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700613 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700614 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700615 }
Adam Cohen1697b792013-09-17 19:08:21 -0700616 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700617 }
618
619 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800620 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700621 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800622 }
623
624 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700625 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700626 // In free scroll mode, we clamp the scrollX
627 if (mFreeScroll) {
628 x = Math.min(x, mFreeScrollMaxScrollX);
629 x = Math.max(x, mFreeScrollMinScrollX);
630 }
631
Adam Cohen0ffac432013-07-10 11:19:26 -0700632 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800633 mUnboundedScrollX = x;
634
Adam Cohen0ffac432013-07-10 11:19:26 -0700635 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
636 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
637 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800638 super.scrollTo(0, y);
639 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700640 if (isRtl) {
641 overScroll(x - mMaxScrollX);
642 } else {
643 overScroll(x);
644 }
Adam Cohen68d73932010-11-15 10:50:58 -0800645 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700646 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800647 super.scrollTo(mMaxScrollX, y);
648 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700649 if (isRtl) {
650 overScroll(x);
651 } else {
652 overScroll(x - mMaxScrollX);
653 }
Adam Cohen68d73932010-11-15 10:50:58 -0800654 }
655 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800656 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800657 super.scrollTo(x, y);
658 }
659
Michael Jurka0142d492010-08-25 17:46:15 -0700660 mTouchX = x;
661 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700662
663 // Update the last motion events when scrolling
664 if (isReordering(true)) {
665 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
666 mLastMotionX = p[0];
667 mLastMotionY = p[1];
668 updateDragViewTranslationDuringDrag();
669 }
Michael Jurka0142d492010-08-25 17:46:15 -0700670 }
671
Adam Cohen53805212013-10-01 10:39:23 -0700672 private void sendScrollAccessibilityEvent() {
673 AccessibilityManager am =
674 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
675 if (am.isEnabled()) {
676 AccessibilityEvent ev =
677 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
Adam Cohen53805212013-10-01 10:39:23 -0700678 ev.setItemCount(getChildCount());
679 ev.setFromIndex(mCurrentPage);
Adam Cohene4602ae2013-10-31 15:46:45 -0700680 ev.setToIndex(getNextPage());
Adam Cohen53805212013-10-01 10:39:23 -0700681
Alan Viverette254139a2013-10-08 13:13:46 -0700682 final int action;
Adam Cohen53805212013-10-01 10:39:23 -0700683 if (getNextPage() >= mCurrentPage) {
684 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD;
685 } else {
686 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
687 }
688
689 ev.setAction(action);
690 sendAccessibilityEventUnchecked(ev);
691 }
692 }
693
Michael Jurka0142d492010-08-25 17:46:15 -0700694 // we moved this functionality to a helper function so SmoothPagedView can reuse it
695 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700696 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700697 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700698 if (getScrollX() != mScroller.getCurrX()
699 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700700 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700701 float scaleX = mFreeScroll ? getScaleX() : 1f;
702 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
703 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700704 }
Michael Jurka0142d492010-08-25 17:46:15 -0700705 invalidate();
706 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700707 } else if (mNextPage != INVALID_PAGE) {
Adam Cohen53805212013-10-01 10:39:23 -0700708 sendScrollAccessibilityEvent();
709
Winson Chung86f77532010-08-24 11:08:22 -0700710 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700711 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700712 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700713
Winson Chung9c0565f2013-07-19 13:49:06 -0700714 // Load the associated pages if necessary
715 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
716 loadAssociatedPages(mCurrentPage);
717 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
718 }
719
Adam Cohen73aa9752010-11-24 16:26:58 -0800720 // We don't want to trigger a page end moving unless the page has settled
721 // and the user has stopped scrolling
722 if (mTouchState == TOUCH_STATE_REST) {
723 pageEndMoving();
724 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700725
Adam Cohen7d30a372013-07-01 17:03:59 -0700726 onPostReorderingAnimationCompleted();
Adam Cohen53805212013-10-01 10:39:23 -0700727 AccessibilityManager am = (AccessibilityManager)
Adam Cohen0ffac432013-07-10 11:19:26 -0700728 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
Adam Cohen53805212013-10-01 10:39:23 -0700729 if (am.isEnabled()) {
730 // Notify the user when the page changes
731 announceForAccessibility(getCurrentPageDescription());
Adam Cohen0ffac432013-07-10 11:19:26 -0700732 }
Michael Jurka0142d492010-08-25 17:46:15 -0700733 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700734 }
Michael Jurka0142d492010-08-25 17:46:15 -0700735 return false;
736 }
737
738 @Override
739 public void computeScroll() {
740 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700741 }
742
Adam Cohen7d30a372013-07-01 17:03:59 -0700743 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
744 return mTopAlignPageWhenShrinkingForBouncer;
745 }
746
Adam Cohen96d30a12013-07-16 18:13:21 -0700747 public static class LayoutParams extends ViewGroup.LayoutParams {
748 public boolean isFullScreenPage = false;
749
750 /**
751 * {@inheritDoc}
752 */
753 public LayoutParams(int width, int height) {
754 super(width, height);
755 }
756
757 public LayoutParams(ViewGroup.LayoutParams source) {
758 super(source);
759 }
760 }
761
762 protected LayoutParams generateDefaultLayoutParams() {
763 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
764 }
765
Adam Cohenedb40762013-07-18 16:45:45 -0700766 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700767 LayoutParams lp = generateDefaultLayoutParams();
768 lp.isFullScreenPage = true;
769 super.addView(page, 0, lp);
770 }
771
Adam Cohen410f3cd2013-09-22 12:09:32 -0700772 public int getNormalChildHeight() {
773 return mNormalChildHeight;
774 }
775
Winson Chung321e9ee2010-08-09 13:37:56 -0700776 @Override
777 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700778 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700779 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
780 return;
781 }
782
Adam Cohen7d30a372013-07-01 17:03:59 -0700783 // We measure the dimensions of the PagedView to be larger than the pages so that when we
784 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700785 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
786 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
787 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700788 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700789 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
790 // viewport, we can be at most one and a half screens offset once we scale down
791 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohen3b185e22013-10-29 14:45:58 -0700792 int maxSize = Math.max(dm.widthPixels + mInsets.left + mInsets.right,
793 dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700794
Adam Cohen3b185e22013-10-29 14:45:58 -0700795 int parentWidthSize = (int) (1.5f * maxSize);
796 int parentHeightSize = maxSize;
Winson Chungc58497e2013-09-03 17:48:37 -0700797 int scaledWidthSize, scaledHeightSize;
798 if (mUseMinScale) {
Winson Chungc58497e2013-09-03 17:48:37 -0700799 scaledWidthSize = (int) (parentWidthSize / mMinScale);
800 scaledHeightSize = (int) (parentHeightSize / mMinScale);
801 } else {
802 scaledWidthSize = widthSize;
803 scaledHeightSize = heightSize;
804 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700805 mViewport.set(0, 0, widthSize, heightSize);
806
807 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
808 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
809 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700810 }
811
Winson Chung8aad6102012-05-11 16:27:49 -0700812 // Return early if we aren't given a proper dimension
813 if (widthSize <= 0 || heightSize <= 0) {
814 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
815 return;
816 }
817
Adam Lesinski6b879f02010-11-04 16:15:23 -0700818 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
819 * of the All apps view on XLarge displays to not take up more space then it needs. Width
820 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
821 * each page to have the same width.
822 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700823 final int verticalPadding = getPaddingTop() + getPaddingBottom();
824 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700825
826 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700827 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700828 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700829 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
830 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
831 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
832 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700833 final int childCount = getChildCount();
834 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700835 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700836 final View child = getPageAt(i);
Vladimir Marko2824b072013-10-04 16:42:17 +0100837 if (child.getVisibility() != GONE) {
838 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700839
Vladimir Marko2824b072013-10-04 16:42:17 +0100840 int childWidthMode;
841 int childHeightMode;
842 int childWidth;
843 int childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700844
Vladimir Marko2824b072013-10-04 16:42:17 +0100845 if (!lp.isFullScreenPage) {
846 if (lp.width == LayoutParams.WRAP_CONTENT) {
847 childWidthMode = MeasureSpec.AT_MOST;
848 } else {
849 childWidthMode = MeasureSpec.EXACTLY;
850 }
851
852 if (lp.height == LayoutParams.WRAP_CONTENT) {
853 childHeightMode = MeasureSpec.AT_MOST;
854 } else {
855 childHeightMode = MeasureSpec.EXACTLY;
856 }
857
Adam Cohen3b185e22013-10-29 14:45:58 -0700858 childWidth = getViewportWidth() - horizontalPadding
859 - mInsets.left - mInsets.right;
860 childHeight = getViewportHeight() - verticalPadding
861 - mInsets.top - mInsets.bottom;
Vladimir Marko2824b072013-10-04 16:42:17 +0100862 mNormalChildHeight = childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700863 } else {
864 childWidthMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700865 childHeightMode = MeasureSpec.EXACTLY;
Vladimir Marko2824b072013-10-04 16:42:17 +0100866
Adam Cohen3b185e22013-10-29 14:45:58 -0700867 childWidth = getViewportWidth() - mInsets.left - mInsets.right;
868 childHeight = getViewportHeight();
Adam Cohen96d30a12013-07-16 18:13:21 -0700869 }
870
Vladimir Marko2824b072013-10-04 16:42:17 +0100871 final int childWidthMeasureSpec =
872 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
873 final int childHeightMeasureSpec =
874 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
875 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700876 }
Adam Lesinski6b879f02010-11-04 16:15:23 -0700877 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700878 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Adam Cohen60b07122011-11-14 17:26:06 -0800879 }
880
Winson Chung321e9ee2010-08-09 13:37:56 -0700881 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700882 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700883 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700884 return;
885 }
886
Winson Chung785d2eb2011-04-14 16:08:02 -0700887 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700888 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700889
Adam Cohen7d30a372013-07-01 17:03:59 -0700890 int offsetX = getViewportOffsetX();
891 int offsetY = getViewportOffsetY();
892
893 // Update the viewport offsets
894 mViewport.offset(offsetX, offsetY);
895
Adam Cohen0ffac432013-07-10 11:19:26 -0700896 final boolean isRtl = isLayoutRtl();
897
898 final int startIndex = isRtl ? childCount - 1 : 0;
899 final int endIndex = isRtl ? -1 : childCount;
900 final int delta = isRtl ? -1 : 1;
901
Adam Cohen7d30a372013-07-01 17:03:59 -0700902 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700903
Adam Cohen3b185e22013-10-29 14:45:58 -0700904 LayoutParams lp = (LayoutParams) getChildAt(startIndex).getLayoutParams();
905
906 int childLeft = offsetX + (lp.isFullScreenPage ? 0 : getPaddingLeft());
Adam Cohenedb40762013-07-18 16:45:45 -0700907 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
908 mPageScrolls = new int[getChildCount()];
909 }
910
Adam Cohen0ffac432013-07-10 11:19:26 -0700911 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700912 final View child = getPageAt(i);
Winson Chung321e9ee2010-08-09 13:37:56 -0700913 if (child.getVisibility() != View.GONE) {
Adam Cohen3b185e22013-10-29 14:45:58 -0700914 lp = (LayoutParams) child.getLayoutParams();
Vladimir Marko2824b072013-10-04 16:42:17 +0100915 int childTop;
916 if (lp.isFullScreenPage) {
917 childTop = offsetY;
918 } else {
919 childTop = offsetY + getPaddingTop() + mInsets.top;
920 if (mCenterPagesVertically) {
921 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
922 }
923 }
924
Adam Cohen96d30a12013-07-16 18:13:21 -0700925 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700926 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800927
Winson Chung785d2eb2011-04-14 16:08:02 -0700928 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700929 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800930 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700931
Adam Cohen3b185e22013-10-29 14:45:58 -0700932 int scrollOffsetLeft = lp.isFullScreenPage ? 0 : getPaddingLeft();
933 mPageScrolls[i] = childLeft - scrollOffsetLeft - offsetX;
934 childLeft += childWidth + mPageSpacing;
Winson Chung321e9ee2010-08-09 13:37:56 -0700935 }
936 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700937
938 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
939 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800940 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700941 setHorizontalScrollBarEnabled(true);
942 mFirstLayout = false;
943 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700944
945 if (childCount > 0) {
946 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700947 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700948 } else {
949 mMaxScrollX = 0;
950 }
951
952 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
953 !mDeferringForDelete) {
Adam Cohen21cd0022013-10-09 18:57:02 -0700954 if (mRestorePage != INVALID_RESTORE_PAGE) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700955 setCurrentPage(mRestorePage);
Adam Cohen21cd0022013-10-09 18:57:02 -0700956 mRestorePage = INVALID_RESTORE_PAGE;
Winson Chung8c87cd82013-07-23 16:20:10 -0700957 } else {
958 setCurrentPage(getNextPage());
959 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700960 }
961 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700962
963 if (isReordering(true)) {
964 updateDragViewTranslationDuringDrag();
965 }
Winson Chunge3193b92010-09-10 11:44:42 -0700966 }
967
Adam Cohen3b185e22013-10-29 14:45:58 -0700968 public void setPageSpacing(int pageSpacing) {
969 mPageSpacing = pageSpacing;
970 requestLayout();
971 }
972
Adam Cohenf34bab52010-09-30 14:11:56 -0700973 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700974 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
975
976 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700977 for (int i = 0; i < getChildCount(); i++) {
978 View child = getChildAt(i);
979 if (child != null) {
980 float scrollProgress = getScrollProgress(screenCenter, child, i);
981 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800982 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700983 }
984 }
985 invalidate();
986 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700987 }
988
Winson Chungc58497e2013-09-03 17:48:37 -0700989 protected void enablePagedViewAnimations() {
990 mAllowPagedViewAnimations = true;
991
992 }
993 protected void disablePagedViewAnimations() {
994 mAllowPagedViewAnimations = false;
995 }
996
Winson Chunge3193b92010-09-10 11:44:42 -0700997 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700998 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700999 // Update the page indicator, we don't update the page indicator as we
1000 // add/remove pages
1001 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -07001002 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -07001003 mPageIndicator.addMarker(pageIndex,
1004 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -07001005 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001006 }
1007
Adam Cohen2591f6a2011-10-25 14:36:40 -07001008 // This ensures that when children are added, they get the correct transforms / alphas
1009 // in accordance with any scroll effects.
1010 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001011 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001012 invalidate();
1013 }
1014
Michael Jurka8b805b12012-04-18 14:23:14 -07001015 @Override
1016 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001017 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001018 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001019 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001020 }
1021
Winson Chungd2be3812013-07-16 11:11:32 -07001022 private void removeMarkerForView(int index) {
1023 // Update the page indicator, we don't update the page indicator as we
1024 // add/remove pages
1025 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001026 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001027 }
1028 }
1029
1030 @Override
1031 public void removeView(View v) {
1032 // XXX: We should find a better way to hook into this before the view
1033 // gets removed form its parent...
1034 removeMarkerForView(indexOfChild(v));
1035 super.removeView(v);
1036 }
1037 @Override
1038 public void removeViewInLayout(View v) {
1039 // XXX: We should find a better way to hook into this before the view
1040 // gets removed form its parent...
1041 removeMarkerForView(indexOfChild(v));
1042 super.removeViewInLayout(v);
1043 }
1044 @Override
1045 public void removeViewAt(int index) {
1046 // XXX: We should find a better way to hook into this before the view
1047 // gets removed form its parent...
1048 removeViewAt(index);
1049 super.removeViewAt(index);
1050 }
1051 @Override
1052 public void removeAllViewsInLayout() {
1053 // Update the page indicator, we don't update the page indicator as we
1054 // add/remove pages
1055 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001056 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001057 }
1058
1059 super.removeAllViewsInLayout();
1060 }
1061
Adam Cohen73894962011-10-31 13:17:17 -07001062 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001063 if (index < 0 || index > getChildCount() - 1) return 0;
1064
Adam Cohenf698c6e2013-07-17 18:44:25 -07001065 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001066
Adam Cohenf698c6e2013-07-17 18:44:25 -07001067 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001068 }
1069
Adam Cohenf358a4b2013-07-23 16:47:31 -07001070 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001071 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001072 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001073 }
1074
Michael Jurkadde558b2011-11-09 22:09:06 -08001075 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001076 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001077 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001078
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001079 range[0] = -1;
1080 range[1] = -1;
1081
Michael Jurkac4fb9172010-09-02 17:19:20 -07001082 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001083 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001084 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001085
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001086 int count = getChildCount();
1087 for (int i = 0; i < count; i++) {
1088 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001089
Winson Chungc9ca2982013-07-19 12:07:38 -07001090 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001091 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001092 if (mTmpIntPoint[0] > viewportWidth) {
1093 if (range[0] == -1) {
1094 continue;
1095 } else {
1096 break;
1097 }
1098 }
1099
Adam Cohen6a678da2013-09-24 10:58:01 -07001100 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001101 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1102 if (mTmpIntPoint[0] < 0) {
1103 if (range[0] == -1) {
1104 continue;
1105 } else {
1106 break;
1107 }
1108 }
1109 curScreen = i;
1110 if (range[0] < 0) {
1111 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001112 }
1113 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001114
1115 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001116 } else {
1117 range[0] = -1;
1118 range[1] = -1;
1119 }
1120 }
1121
Michael Jurka920d7f42012-05-14 16:29:55 -07001122 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001123 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001124 }
1125
Michael Jurkadde558b2011-11-09 22:09:06 -08001126 @Override
1127 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001128 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001129 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1130 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001131 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001132
1133 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001134 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1135 // set it for the next frame
1136 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001137 screenScrolled(screenCenter);
1138 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001139 }
1140
1141 // Find out which screens are visible; as an optimization we only call draw on them
1142 final int pageCount = getChildCount();
1143 if (pageCount > 0) {
1144 getVisiblePages(mTempVisiblePagesRange);
1145 final int leftScreen = mTempVisiblePagesRange[0];
1146 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001147 if (leftScreen != -1 && rightScreen != -1) {
1148 final long drawingTime = getDrawingTime();
1149 // Clip to the bounds
1150 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001151 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1152 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001153
Adam Cohen7d30a372013-07-01 17:03:59 -07001154 // Draw all the children, leaving the drag view for last
1155 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001156 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001157 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001158 if (mForceDrawAllChildrenNextFrame ||
1159 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001160 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001161 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001162 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001163 // Draw the drag view on top (if there is one)
1164 if (mDragView != null) {
1165 drawChild(canvas, mDragView, drawingTime);
1166 }
1167
Michael Jurka5e368ff2012-05-14 23:13:15 -07001168 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001169 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001170 }
Michael Jurka0142d492010-08-25 17:46:15 -07001171 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001172 }
1173
1174 @Override
1175 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001176 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001177 if (page != mCurrentPage || !mScroller.isFinished()) {
1178 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001179 return true;
1180 }
1181 return false;
1182 }
1183
1184 @Override
1185 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001186 int focusablePage;
1187 if (mNextPage != INVALID_PAGE) {
1188 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001189 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001190 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001191 }
Winson Chung86f77532010-08-24 11:08:22 -07001192 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001193 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001194 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001195 }
1196 return false;
1197 }
1198
1199 @Override
1200 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001201 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001202 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001203 if (getCurrentPage() > 0) {
1204 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001205 return true;
1206 }
1207 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001208 if (getCurrentPage() < getPageCount() - 1) {
1209 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001210 return true;
1211 }
1212 }
1213 return super.dispatchUnhandledMove(focused, direction);
1214 }
1215
1216 @Override
1217 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001218 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001219 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001220 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001221 }
1222 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001223 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001224 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001225 }
1226 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001227 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001228 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001229 }
1230 }
1231 }
1232
1233 /**
1234 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001235 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001236 *
Winson Chung86f77532010-08-24 11:08:22 -07001237 * This happens when live folders requery, and if they're off page, they
1238 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001239 */
1240 @Override
1241 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001242 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001243 View v = focused;
1244 while (true) {
1245 if (v == current) {
1246 super.focusableViewAvailable(focused);
1247 return;
1248 }
1249 if (v == this) {
1250 return;
1251 }
1252 ViewParent parent = v.getParent();
1253 if (parent instanceof View) {
1254 v = (View)v.getParent();
1255 } else {
1256 return;
1257 }
1258 }
1259 }
1260
1261 /**
1262 * {@inheritDoc}
1263 */
1264 @Override
1265 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1266 if (disallowIntercept) {
1267 // We need to make sure to cancel our long press if
1268 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001269 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001270 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001271 }
1272 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1273 }
1274
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001275 /**
1276 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1277 */
1278 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001279 if (isLayoutRtl()) {
1280 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohen3b185e22013-10-29 14:45:58 -07001281 getPaddingRight() - mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001282 }
Adam Cohen3b185e22013-10-29 14:45:58 -07001283 return (x < getViewportOffsetX() + getPaddingLeft() + mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001284 }
1285
1286 /**
1287 * Return true if a tap at (x, y) should trigger a flip to the next page.
1288 */
1289 protected boolean hitsNextPage(float x, float y) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001290 if (isLayoutRtl()) {
Adam Cohen3b185e22013-10-29 14:45:58 -07001291 return (x < getViewportOffsetX() + getPaddingLeft() + mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001292 }
1293 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohen3b185e22013-10-29 14:45:58 -07001294 getPaddingRight() - mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001295 }
Winson Chung52aee602013-01-30 12:01:02 -08001296
Adam Cohen7d30a372013-07-01 17:03:59 -07001297 /** Returns whether x and y originated within the buffered viewport */
1298 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1299 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1300 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1301 return mTmpRect.contains(x, y);
1302 }
1303
Winson Chung321e9ee2010-08-09 13:37:56 -07001304 @Override
1305 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001306 if (DISABLE_TOUCH_INTERACTION) {
1307 return false;
1308 }
1309
Winson Chung321e9ee2010-08-09 13:37:56 -07001310 /*
1311 * This method JUST determines whether we want to intercept the motion.
1312 * If we return true, onTouchEvent will be called and we do the actual
1313 * scrolling there.
1314 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001315 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001316
Winson Chung45e1d6e2010-11-09 17:19:49 -08001317 // Skip touch handling if there are no pages to swipe
1318 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1319
Winson Chung321e9ee2010-08-09 13:37:56 -07001320 /*
1321 * Shortcut the most recurring case: the user is in the dragging
1322 * state and he is moving his finger. We want to intercept this
1323 * motion.
1324 */
1325 final int action = ev.getAction();
1326 if ((action == MotionEvent.ACTION_MOVE) &&
1327 (mTouchState == TOUCH_STATE_SCROLLING)) {
1328 return true;
1329 }
1330
Winson Chung321e9ee2010-08-09 13:37:56 -07001331 switch (action & MotionEvent.ACTION_MASK) {
1332 case MotionEvent.ACTION_MOVE: {
1333 /*
1334 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1335 * whether the user has moved far enough from his original down touch.
1336 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001337 if (mActivePointerId != INVALID_POINTER) {
1338 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001339 }
1340 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1341 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1342 // i.e. fall through to the next case (don't break)
1343 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1344 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001345 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001346 }
1347
1348 case MotionEvent.ACTION_DOWN: {
1349 final float x = ev.getX();
1350 final float y = ev.getY();
1351 // Remember location of down touch
1352 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001353 mDownMotionY = y;
1354 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 mLastMotionX = x;
1356 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001357 float[] p = mapPointFromViewToParent(this, x, y);
1358 mParentDownMotionX = p[0];
1359 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001360 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001361 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001362 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001363
Winson Chung321e9ee2010-08-09 13:37:56 -07001364 /*
1365 * If being flinged and user touches the screen, initiate drag;
1366 * otherwise don't. mScroller.isFinished should be false when
1367 * being flinged.
1368 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001369 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001370 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
Adam Cohen2da0a052013-11-08 06:28:17 -08001371
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001372 if (finishedScrolling) {
1373 mTouchState = TOUCH_STATE_REST;
Adam Cohen2da0a052013-11-08 06:28:17 -08001374 if (!mScroller.isFinished()) {
1375 mScrollAbortedFromIntercept = true;
1376 abortScrollerAnimation(false);
1377 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001378 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001379 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1380 mTouchState = TOUCH_STATE_SCROLLING;
1381 } else {
1382 mTouchState = TOUCH_STATE_REST;
1383 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001384 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001385
Winson Chung86f77532010-08-24 11:08:22 -07001386 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001387 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001388 if (!DISABLE_TOUCH_SIDE_PAGES) {
1389 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1390 if (getChildCount() > 0) {
1391 if (hitsPreviousPage(x, y)) {
1392 mTouchState = TOUCH_STATE_PREV_PAGE;
1393 } else if (hitsNextPage(x, y)) {
1394 mTouchState = TOUCH_STATE_NEXT_PAGE;
1395 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001396 }
1397 }
1398 }
1399 break;
1400 }
1401
Winson Chung321e9ee2010-08-09 13:37:56 -07001402 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001403 case MotionEvent.ACTION_CANCEL:
Adam Cohencae7f572013-11-04 14:42:52 -08001404 if (mScrollAbortedFromIntercept) {
1405 snapToDestination();
1406 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001407 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001408 break;
1409
1410 case MotionEvent.ACTION_POINTER_UP:
1411 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001412 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001413 break;
1414 }
1415
1416 /*
1417 * The only time we want to intercept motion events is if we are in the
1418 * drag mode.
1419 */
1420 return mTouchState != TOUCH_STATE_REST;
1421 }
1422
Adam Cohenf8d28232011-02-01 21:47:00 -08001423 protected void determineScrollingStart(MotionEvent ev) {
1424 determineScrollingStart(ev, 1.0f);
1425 }
1426
Winson Chung321e9ee2010-08-09 13:37:56 -07001427 /*
1428 * Determines if we should change the touch state to start scrolling after the
1429 * user moves their touch point too far.
1430 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001431 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001432 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001433 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001434 if (pointerIndex == -1) return;
1435
1436 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001437 final float x = ev.getX(pointerIndex);
1438 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001439 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1440
Winson Chung321e9ee2010-08-09 13:37:56 -07001441 final int xDiff = (int) Math.abs(x - mLastMotionX);
1442 final int yDiff = (int) Math.abs(y - mLastMotionY);
1443
Adam Cohenf8d28232011-02-01 21:47:00 -08001444 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001445 boolean xPaged = xDiff > mPagingTouchSlop;
1446 boolean xMoved = xDiff > touchSlop;
1447 boolean yMoved = yDiff > touchSlop;
1448
Adam Cohenf8d28232011-02-01 21:47:00 -08001449 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001450 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001451 // Scroll if the user moved far enough along the X axis
1452 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001453 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001454 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001455 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001456 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001457 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1458 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001459 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001460 }
1461 }
1462
Adam Cohen7d30a372013-07-01 17:03:59 -07001463 protected float getMaxScrollProgress() {
1464 return 1.0f;
1465 }
1466
Adam Cohenf8d28232011-02-01 21:47:00 -08001467 protected void cancelCurrentPageLongPress() {
1468 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001469 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001470 // Try canceling the long press. It could also have been scheduled
1471 // by a distant descendant, so use the mAllowLongPress flag to block
1472 // everything
1473 final View currentPage = getPageAt(mCurrentPage);
1474 if (currentPage != null) {
1475 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001476 }
1477 }
1478 }
1479
Adam Cohen7d30a372013-07-01 17:03:59 -07001480 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1481 final int halfScreenSize = getViewportWidth() / 2;
1482
1483 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1484 screenCenter = Math.max(halfScreenSize, screenCenter);
1485
1486 return getScrollProgress(screenCenter, v, page);
1487 }
1488
Adam Cohenb5ba0972011-09-07 18:02:31 -07001489 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001490 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001491
Adam Cohenedb40762013-07-18 16:45:45 -07001492 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohen3b185e22013-10-29 14:45:58 -07001493 int count = getChildCount();
1494
1495 final int totalDistance;
1496
1497 int adjacentPage = page + 1;
1498 if ((delta < 0 && !isLayoutRtl()) || (delta > 0 && isLayoutRtl())) {
1499 adjacentPage = page - 1;
1500 }
1501
1502 if (adjacentPage < 0 || adjacentPage > count - 1) {
1503 totalDistance = v.getMeasuredWidth() + mPageSpacing;
1504 } else {
1505 totalDistance = Math.abs(getScrollForPage(adjacentPage) - getScrollForPage(page));
1506 }
Adam Cohenb5ba0972011-09-07 18:02:31 -07001507
1508 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001509 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1510 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001511 return scrollProgress;
1512 }
1513
Adam Cohenedb40762013-07-18 16:45:45 -07001514 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001515 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001516 return 0;
1517 } else {
1518 return mPageScrolls[index];
1519 }
1520 }
1521
Adam Cohen564a2e72013-10-09 14:47:32 -07001522 // While layout transitions are occurring, a child's position may stray from its baseline
1523 // position. This method returns the magnitude of this stray at any given time.
1524 public int getLayoutTransitionOffsetForPage(int index) {
1525 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1526 return 0;
1527 } else {
1528 View child = getChildAt(index);
Adam Cohen3b185e22013-10-29 14:45:58 -07001529
1530 int scrollOffset = 0;
1531 LayoutParams lp = (LayoutParams) child.getLayoutParams();
1532 if (!lp.isFullScreenPage) {
1533 scrollOffset = isLayoutRtl() ? getPaddingRight() : getPaddingLeft();
1534 }
1535
Adam Cohen564a2e72013-10-09 14:47:32 -07001536 int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
1537 return (int) (child.getX() - baselineX);
1538 }
1539 }
1540
Adam Cohene0f66b52010-11-23 15:06:07 -08001541 // This curve determines how the effect of scrolling over the limits of the page dimishes
1542 // as the user pulls further and further from the bounds
1543 private float overScrollInfluenceCurve(float f) {
1544 f -= 1.0f;
1545 return f * f * f + 1.0f;
1546 }
1547
Adam Cohenb5ba0972011-09-07 18:02:31 -07001548 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001549 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001550
1551 // We want to reach the max over scroll effect when the user has
1552 // over scrolled half the size of the screen
1553 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1554
1555 if (f == 0) return;
1556
1557 // Clamp this factor, f, to -1 < f < 1
1558 if (Math.abs(f) >= 1) {
1559 f /= Math.abs(f);
1560 }
1561
1562 int overScrollAmount = (int) Math.round(f * screenSize);
1563 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001564 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001565 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001566 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001567 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001568 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001569 }
1570 invalidate();
1571 }
1572
1573 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001574 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001575
1576 float f = (amount / screenSize);
1577
1578 if (f == 0) return;
1579 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1580
Adam Cohen7bfc9792011-01-28 13:52:37 -08001581 // Clamp this factor, f, to -1 < f < 1
1582 if (Math.abs(f) >= 1) {
1583 f /= Math.abs(f);
1584 }
1585
Adam Cohene0f66b52010-11-23 15:06:07 -08001586 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001587 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001588 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001589 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001590 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001591 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001592 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001593 }
1594 invalidate();
1595 }
1596
Adam Cohenb5ba0972011-09-07 18:02:31 -07001597 protected void overScroll(float amount) {
1598 dampedOverScroll(amount);
1599 }
1600
Michael Jurkac5b262c2011-01-12 20:24:50 -08001601 protected float maxOverScroll() {
1602 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001603 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001604 float f = 1.0f;
1605 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1606 return OVERSCROLL_DAMP_FACTOR * f;
1607 }
1608
Adam Cohenf358a4b2013-07-23 16:47:31 -07001609 protected void enableFreeScroll() {
1610 setEnableFreeScroll(true, -1);
1611 }
1612
1613 protected void disableFreeScroll(int snapPage) {
1614 setEnableFreeScroll(false, snapPage);
1615 }
1616
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001617 void updateFreescrollBounds() {
1618 getOverviewModePages(mTempVisiblePagesRange);
1619 if (isLayoutRtl()) {
1620 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1621 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1622 } else {
1623 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1624 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1625 }
1626 }
1627
Adam Cohenf358a4b2013-07-23 16:47:31 -07001628 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1629 mFreeScroll = freeScroll;
1630
1631 if (snapPage == -1) {
1632 snapPage = getPageNearestToCenterOfScreen();
1633 }
1634
Adam Cohenf358a4b2013-07-23 16:47:31 -07001635 if (!mFreeScroll) {
1636 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001637 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001638 updateFreescrollBounds();
1639 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001640 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1641 setCurrentPage(mTempVisiblePagesRange[0]);
1642 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1643 setCurrentPage(mTempVisiblePagesRange[1]);
1644 }
1645 }
1646
1647 setEnableOverscroll(!freeScroll);
1648 }
1649
1650 private void setEnableOverscroll(boolean enable) {
1651 mAllowOverScroll = enable;
1652 }
1653
1654 int getNearestHoverOverPageIndex() {
1655 if (mDragView != null) {
1656 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1657 + mDragView.getTranslationX());
1658 getOverviewModePages(mTempVisiblePagesRange);
1659 int minDistance = Integer.MAX_VALUE;
1660 int minIndex = indexOfChild(mDragView);
1661 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1662 View page = getPageAt(i);
1663 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1664 int d = Math.abs(dragX - pageX);
1665 if (d < minDistance) {
1666 minIndex = i;
1667 minDistance = d;
1668 }
1669 }
1670 return minIndex;
1671 }
1672 return -1;
1673 }
1674
Winson Chung321e9ee2010-08-09 13:37:56 -07001675 @Override
1676 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001677 if (DISABLE_TOUCH_INTERACTION) {
1678 return false;
1679 }
1680
Adam Cohen1697b792013-09-17 19:08:21 -07001681 super.onTouchEvent(ev);
1682
Winson Chung45e1d6e2010-11-09 17:19:49 -08001683 // Skip touch handling if there are no pages to swipe
1684 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1685
Michael Jurkab8f06722010-10-10 15:58:46 -07001686 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001687
1688 final int action = ev.getAction();
1689
1690 switch (action & MotionEvent.ACTION_MASK) {
1691 case MotionEvent.ACTION_DOWN:
1692 /*
1693 * If being flinged and user touches, stop the fling. isFinished
1694 * will be false if being flinged.
1695 */
1696 if (!mScroller.isFinished()) {
Adam Cohen8bdbaab2013-10-29 15:25:02 -07001697 abortScrollerAnimation(false);
Winson Chung321e9ee2010-08-09 13:37:56 -07001698 }
1699
1700 // Remember where the motion event started
1701 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001702 mDownMotionY = mLastMotionY = ev.getY();
1703 mDownScrollX = getScrollX();
1704 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1705 mParentDownMotionX = p[0];
1706 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001707 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001708 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001709 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001710
Michael Jurka0142d492010-08-25 17:46:15 -07001711 if (mTouchState == TOUCH_STATE_SCROLLING) {
1712 pageBeginMoving();
1713 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001714 break;
1715
1716 case MotionEvent.ACTION_MOVE:
1717 if (mTouchState == TOUCH_STATE_SCROLLING) {
1718 // Scroll to follow the motion event
1719 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001720
1721 if (pointerIndex == -1) return true;
1722
Winson Chung321e9ee2010-08-09 13:37:56 -07001723 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001724 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001725
Adam Cohenaefd4e12011-02-14 16:39:38 -08001726 mTotalMotionX += Math.abs(deltaX);
1727
Winson Chungc0844aa2011-02-02 15:25:58 -08001728 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1729 // keep the remainder because we are actually testing if we've moved from the last
1730 // scrolled position (which is discrete).
1731 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001732 mTouchX += deltaX;
1733 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1734 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001735 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001736 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001737 } else {
1738 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001739 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001740 mLastMotionX = x;
1741 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001742 } else {
1743 awakenScrollBars();
1744 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001745 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1746 // Update the last motion position
1747 mLastMotionX = ev.getX();
1748 mLastMotionY = ev.getY();
1749
1750 // Update the parent down so that our zoom animations take this new movement into
1751 // account
1752 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1753 mParentDownMotionX = pt[0];
1754 mParentDownMotionY = pt[1];
1755 updateDragViewTranslationDuringDrag();
1756
1757 // Find the closest page to the touch point
1758 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001759
1760 // Change the drag view if we are hovering over the drop target
1761 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1762 (int) mParentDownMotionX, (int) mParentDownMotionY);
1763 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1764
Adam Cohen7d30a372013-07-01 17:03:59 -07001765 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1766 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1767 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1768 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1769
Adam Cohenf358a4b2013-07-23 16:47:31 -07001770 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1771 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1772 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001773 mTempVisiblePagesRange[0] = 0;
1774 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001775 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001776 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1777 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1778 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1779 mSidePageHoverIndex = pageUnderPointIndex;
1780 mSidePageHoverRunnable = new Runnable() {
1781 @Override
1782 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001783 // Setup the scroll to the correct page before we swap the views
1784 snapToPage(pageUnderPointIndex);
1785
1786 // For each of the pages between the paged view and the drag view,
1787 // animate them from the previous position to the new position in
1788 // the layout (as a result of the drag view moving in the layout)
1789 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1790 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1791 dragViewIndex + 1 : pageUnderPointIndex;
1792 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1793 dragViewIndex - 1 : pageUnderPointIndex;
1794 for (int i = lowerIndex; i <= upperIndex; ++i) {
1795 View v = getChildAt(i);
1796 // dragViewIndex < pageUnderPointIndex, so after we remove the
1797 // drag view all subsequent views to pageUnderPointIndex will
1798 // shift down.
1799 int oldX = getViewportOffsetX() + getChildOffset(i);
1800 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1801
1802 // Animate the view translation from its old position to its new
1803 // position
1804 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1805 if (anim != null) {
1806 anim.cancel();
1807 }
1808
1809 v.setTranslationX(oldX - newX);
1810 anim = new AnimatorSet();
1811 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1812 anim.playTogether(
1813 ObjectAnimator.ofFloat(v, "translationX", 0f));
1814 anim.start();
1815 v.setTag(anim);
1816 }
1817
1818 removeView(mDragView);
1819 onRemoveView(mDragView, false);
1820 addView(mDragView, pageUnderPointIndex);
1821 onAddView(mDragView, pageUnderPointIndex);
1822 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001823 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001824 }
1825 };
1826 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1827 }
1828 } else {
1829 removeCallbacks(mSidePageHoverRunnable);
1830 mSidePageHoverIndex = -1;
1831 }
Adam Cohen564976a2010-10-13 18:52:07 -07001832 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001833 determineScrollingStart(ev);
1834 }
1835 break;
1836
1837 case MotionEvent.ACTION_UP:
1838 if (mTouchState == TOUCH_STATE_SCROLLING) {
1839 final int activePointerId = mActivePointerId;
1840 final int pointerIndex = ev.findPointerIndex(activePointerId);
1841 final float x = ev.getX(pointerIndex);
1842 final VelocityTracker velocityTracker = mVelocityTracker;
1843 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1844 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001845 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001846 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001847 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1848 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001849
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001850 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1851
Adam Cohen00481b32011-11-18 12:03:48 -08001852 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001853 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001854
Adam Cohenf358a4b2013-07-23 16:47:31 -07001855 if (!mFreeScroll) {
1856 // In the case that the page is moved far to one direction and then is flung
1857 // in the opposite direction, we use a threshold to determine whether we should
1858 // just return to the starting page, or if we should skip one further.
1859 boolean returnToOriginalPage = false;
1860 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1861 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1862 returnToOriginalPage = true;
1863 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001864
Adam Cohenf358a4b2013-07-23 16:47:31 -07001865 int finalPage;
1866 // We give flings precedence over large moves, which is why we short-circuit our
1867 // test for a large move if a fling has been registered. That is, a large
1868 // move to the left and fling to the right will register as a fling to the right.
1869 final boolean isRtl = isLayoutRtl();
1870 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1871 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1872 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1873 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1874 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1875 snapToPageWithVelocity(finalPage, velocityX);
1876 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1877 (isFling && isVelocityXLeft)) &&
1878 mCurrentPage < getChildCount() - 1) {
1879 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1880 snapToPageWithVelocity(finalPage, velocityX);
1881 } else {
1882 snapToDestination();
Adam Cohenf358a4b2013-07-23 16:47:31 -07001883 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001884 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001885 if (!mScroller.isFinished()) {
Adam Cohen8bdbaab2013-10-29 15:25:02 -07001886 abortScrollerAnimation(true);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001887 }
1888
1889 float scaleX = getScaleX();
1890 int vX = (int) (-velocityX * scaleX);
1891 int initialScrollX = (int) (getScrollX() * scaleX);
1892
1893 mScroller.fling(initialScrollX,
1894 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1895 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001896 }
Adam Cohencae7f572013-11-04 14:42:52 -08001897 } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1898 // at this point we have not moved beyond the touch slop
1899 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1900 // we can just page
1901 int nextPage = Math.max(0, mCurrentPage - 1);
1902 if (nextPage != mCurrentPage) {
1903 snapToPage(nextPage);
1904 } else {
1905 snapToDestination();
1906 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001907 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001908 // at this point we have not moved beyond the touch slop
1909 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1910 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001911 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1912 if (nextPage != mCurrentPage) {
1913 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001914 } else {
1915 snapToDestination();
1916 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001917 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1918 // Update the last motion position
1919 mLastMotionX = ev.getX();
1920 mLastMotionY = ev.getY();
1921
1922 // Update the parent down so that our zoom animations take this new movement into
1923 // account
1924 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1925 mParentDownMotionX = pt[0];
1926 mParentDownMotionY = pt[1];
1927 updateDragViewTranslationDuringDrag();
1928 boolean handledFling = false;
1929 if (!DISABLE_FLING_TO_DELETE) {
1930 // Check the velocity and see if we are flinging-to-delete
1931 PointF flingToDeleteVector = isFlingingToDelete();
1932 if (flingToDeleteVector != null) {
1933 onFlingToDelete(flingToDeleteVector);
1934 handledFling = true;
1935 }
1936 }
1937 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1938 (int) mParentDownMotionY)) {
1939 onDropToDelete();
1940 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001941 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001942 if (!mCancelTap) {
1943 onUnhandledTap(ev);
1944 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001945 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001946
1947 // Remove the callback to wait for the side page hover timeout
1948 removeCallbacks(mSidePageHoverRunnable);
1949 // End any intermediate reordering states
1950 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001951 break;
1952
1953 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001954 if (mTouchState == TOUCH_STATE_SCROLLING) {
1955 snapToDestination();
1956 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001957 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001958 break;
1959
1960 case MotionEvent.ACTION_POINTER_UP:
1961 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001962 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001963 break;
1964 }
1965
1966 return true;
1967 }
1968
Adam Cohen7d30a372013-07-01 17:03:59 -07001969 public void onFlingToDelete(View v) {}
1970 public void onRemoveView(View v, boolean deletePermanently) {}
1971 public void onRemoveViewAnimationCompleted() {}
1972 public void onAddView(View v, int index) {}
1973
1974 private void resetTouchState() {
1975 releaseVelocityTracker();
1976 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001977 mCancelTap = false;
Adam Cohencae7f572013-11-04 14:42:52 -08001978 mScrollAbortedFromIntercept = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001979 mTouchState = TOUCH_STATE_REST;
1980 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001981 }
1982
Adam Cohen1697b792013-09-17 19:08:21 -07001983 protected void onUnhandledTap(MotionEvent ev) {
1984 ((Launcher) getContext()).onClick(this);
1985 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001986
Winson Chung185d7162011-02-28 13:47:29 -08001987 @Override
1988 public boolean onGenericMotionEvent(MotionEvent event) {
1989 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1990 switch (event.getAction()) {
1991 case MotionEvent.ACTION_SCROLL: {
1992 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1993 final float vscroll;
1994 final float hscroll;
1995 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1996 vscroll = 0;
1997 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1998 } else {
1999 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
2000 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
2001 }
2002 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07002003 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
2004 : (hscroll > 0 || vscroll > 0);
2005 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08002006 scrollRight();
2007 } else {
2008 scrollLeft();
2009 }
2010 return true;
2011 }
2012 }
2013 }
2014 }
2015 return super.onGenericMotionEvent(event);
2016 }
2017
Michael Jurkab8f06722010-10-10 15:58:46 -07002018 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
2019 if (mVelocityTracker == null) {
2020 mVelocityTracker = VelocityTracker.obtain();
2021 }
2022 mVelocityTracker.addMovement(ev);
2023 }
2024
2025 private void releaseVelocityTracker() {
2026 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002027 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07002028 mVelocityTracker.recycle();
2029 mVelocityTracker = null;
2030 }
2031 }
2032
Winson Chung321e9ee2010-08-09 13:37:56 -07002033 private void onSecondaryPointerUp(MotionEvent ev) {
2034 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
2035 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
2036 final int pointerId = ev.getPointerId(pointerIndex);
2037 if (pointerId == mActivePointerId) {
2038 // This was our active pointer going up. Choose a new
2039 // active pointer and adjust accordingly.
2040 // TODO: Make this decision more intelligent.
2041 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2042 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
2043 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08002044 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07002045 mActivePointerId = ev.getPointerId(newPointerIndex);
2046 if (mVelocityTracker != null) {
2047 mVelocityTracker.clear();
2048 }
2049 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08002050 }
2051
Winson Chung321e9ee2010-08-09 13:37:56 -07002052 @Override
2053 public void requestChildFocus(View child, View focused) {
2054 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002055 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002056 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002057 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002058 }
2059 }
2060
Winson Chung1908d072011-02-24 18:09:44 -08002061 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002062 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002063 }
2064
Adam Cohen7d30a372013-07-01 17:03:59 -07002065 int getPageNearestToPoint(float x) {
2066 int index = 0;
2067 for (int i = 0; i < getChildCount(); ++i) {
2068 if (x < getChildAt(i).getRight() - getScrollX()) {
2069 return index;
2070 } else {
2071 index++;
2072 }
2073 }
2074 return Math.min(index, getChildCount() - 1);
2075 }
2076
Adam Cohend19d3ca2010-09-15 14:43:42 -07002077 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002078 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002079 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002080 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002081 final int childCount = getChildCount();
2082 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002083 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002084 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002085 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002086 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002087 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2088 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2089 minDistanceFromScreenCenter = distanceFromScreenCenter;
2090 minDistanceFromScreenCenterIndex = i;
2091 }
2092 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002093 return minDistanceFromScreenCenterIndex;
2094 }
2095
2096 protected void snapToDestination() {
2097 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002098 }
2099
Adam Cohene0f66b52010-11-23 15:06:07 -08002100 private static class ScrollInterpolator implements Interpolator {
2101 public ScrollInterpolator() {
2102 }
2103
2104 public float getInterpolation(float t) {
2105 t -= 1.0f;
2106 return t*t*t*t*t + 1;
2107 }
2108 }
2109
2110 // We want the duration of the page snap animation to be influenced by the distance that
2111 // the screen has to travel, however, we don't want this duration to be effected in a
2112 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2113 // of travel has on the overall snap duration.
2114 float distanceInfluenceForSnapDuration(float f) {
2115 f -= 0.5f; // center the values about 0.
2116 f *= 0.3f * Math.PI / 2.0f;
2117 return (float) Math.sin(f);
2118 }
2119
Michael Jurka0142d492010-08-25 17:46:15 -07002120 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002121 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002122 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002123
Adam Cohenedb40762013-07-18 16:45:45 -07002124 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002125 int delta = newX - mUnboundedScrollX;
2126 int duration = 0;
2127
Adam Cohen265b9a62011-12-07 14:37:18 -08002128 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002129 // If the velocity is low enough, then treat this more as an automatic page advance
2130 // as opposed to an apparent physical response to flinging
2131 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2132 return;
2133 }
2134
2135 // Here we compute a "distance" that will be used in the computation of the overall
2136 // snap duration. This is a function of the actual distance that needs to be traveled;
2137 // we keep this value close to half screen size in order to reduce the variance in snap
2138 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002139 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002140 float distance = halfScreenSize + halfScreenSize *
2141 distanceInfluenceForSnapDuration(distanceRatio);
2142
2143 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002144 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002145
2146 // we want the page's snap velocity to approximately match the velocity at which the
2147 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002148 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2149 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002150
2151 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002152 }
2153
2154 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002155 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002156 }
2157
Adam Cohen7d30a372013-07-01 17:03:59 -07002158 protected void snapToPageImmediately(int whichPage) {
2159 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2160 }
2161
Michael Jurka0142d492010-08-25 17:46:15 -07002162 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002163 snapToPage(whichPage, duration, false);
2164 }
2165
2166 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002167 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002168
Adam Cohenedb40762013-07-18 16:45:45 -07002169 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002170 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002171 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002172 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002173 }
2174
2175 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002176 snapToPage(whichPage, delta, duration, false);
2177 }
Michael Jurka0142d492010-08-25 17:46:15 -07002178
Adam Cohen7d30a372013-07-01 17:03:59 -07002179 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2180 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002181 View focusedChild = getFocusedChild();
2182 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002183 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002184 focusedChild.clearFocus();
2185 }
2186
Adam Cohen53805212013-10-01 10:39:23 -07002187 sendScrollAccessibilityEvent();
2188
Michael Jurka0142d492010-08-25 17:46:15 -07002189 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002190 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002191 if (immediate) {
2192 duration = 0;
2193 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002194 duration = Math.abs(delta);
2195 }
2196
Adam Cohenf358a4b2013-07-23 16:47:31 -07002197 if (!mScroller.isFinished()) {
2198 mScroller.abortAnimation();
2199 }
Adam Cohen68d73932010-11-15 10:50:58 -08002200 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002201
Michael Jurka0142d492010-08-25 17:46:15 -07002202 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002203
2204 // Trigger a compute() to finish switching pages if necessary
2205 if (immediate) {
2206 computeScroll();
2207 }
2208
Winson Chung9c0565f2013-07-19 13:49:06 -07002209 // Defer loading associated pages until the scroll settles
2210 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2211
Adam Cohen7d30a372013-07-01 17:03:59 -07002212 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002213 invalidate();
2214 }
2215
Winson Chung321e9ee2010-08-09 13:37:56 -07002216 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002217 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002218 }
2219
2220 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002221 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002222 }
2223
Winson Chung86f77532010-08-24 11:08:22 -07002224 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002225 int result = -1;
2226 if (v != null) {
2227 ViewParent vp = v.getParent();
2228 int count = getChildCount();
2229 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002230 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002231 return i;
2232 }
2233 }
2234 }
2235 return result;
2236 }
2237
2238 /**
2239 * @return True is long presses are still allowed for the current touch
2240 */
2241 public boolean allowLongPress() {
2242 return mAllowLongPress;
2243 }
2244
Adam Cohendbdff6b2013-09-18 19:09:15 -07002245 @Override
2246 public boolean performLongClick() {
2247 mCancelTap = true;
2248 return super.performLongClick();
2249 }
2250
Michael Jurka0142d492010-08-25 17:46:15 -07002251 /**
2252 * Set true to allow long-press events to be triggered, usually checked by
2253 * {@link Launcher} to accept or block dpad-initiated long-presses.
2254 */
2255 public void setAllowLongPress(boolean allowLongPress) {
2256 mAllowLongPress = allowLongPress;
2257 }
2258
Winson Chung321e9ee2010-08-09 13:37:56 -07002259 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002260 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002261
2262 SavedState(Parcelable superState) {
2263 super(superState);
2264 }
2265
2266 private SavedState(Parcel in) {
2267 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002268 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002269 }
2270
2271 @Override
2272 public void writeToParcel(Parcel out, int flags) {
2273 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002274 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002275 }
2276
2277 public static final Parcelable.Creator<SavedState> CREATOR =
2278 new Parcelable.Creator<SavedState>() {
2279 public SavedState createFromParcel(Parcel in) {
2280 return new SavedState(in);
2281 }
2282
2283 public SavedState[] newArray(int size) {
2284 return new SavedState[size];
2285 }
2286 };
2287 }
2288
Winson Chungf314b0e2011-08-16 11:54:27 -07002289 protected void loadAssociatedPages(int page) {
2290 loadAssociatedPages(page, false);
2291 }
2292 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002293 if (mContentIsRefreshable) {
2294 final int count = getChildCount();
2295 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002296 int lowerPageBound = getAssociatedLowerPageBound(page);
2297 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002298 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2299 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002300 // First, clear any pages that should no longer be loaded
2301 for (int i = 0; i < count; ++i) {
2302 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002303 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002304 if (layout.getPageChildCount() > 0) {
2305 layout.removeAllViewsOnPage();
2306 }
2307 mDirtyPageContent.set(i, true);
2308 }
2309 }
2310 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002311 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002312 if ((i != page) && immediateAndOnly) {
2313 continue;
2314 }
Michael Jurka0142d492010-08-25 17:46:15 -07002315 if (lowerPageBound <= i && i <= upperPageBound) {
2316 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002317 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002318 mDirtyPageContent.set(i, false);
2319 }
Winson Chung86f77532010-08-24 11:08:22 -07002320 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002321 }
2322 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002323 }
2324 }
2325
Winson Chunge3193b92010-09-10 11:44:42 -07002326 protected int getAssociatedLowerPageBound(int page) {
2327 return Math.max(0, page - 1);
2328 }
2329 protected int getAssociatedUpperPageBound(int page) {
2330 final int count = getChildCount();
2331 return Math.min(page + 1, count - 1);
2332 }
2333
Winson Chung86f77532010-08-24 11:08:22 -07002334 /**
2335 * This method is called ONLY to synchronize the number of pages that the paged view has.
2336 * To actually fill the pages with information, implement syncPageItems() below. It is
2337 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2338 * and therefore, individual page items do not need to be updated in this method.
2339 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002340 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002341
2342 /**
2343 * This method is called to synchronize the items that are on a particular page. If views on
2344 * the page can be reused, then they should be updated within this method.
2345 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002346 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002347
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002348 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002349 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002350 }
2351 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002352 invalidatePageData(currentPage, false);
2353 }
2354 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002355 if (!mIsDataReady) {
2356 return;
2357 }
2358
Michael Jurka0142d492010-08-25 17:46:15 -07002359 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002360 // Force all scrolling-related behavior to end
Adam Cohen4fe4c932013-10-28 16:02:34 -07002361 forceFinishScroller();
Adam Cohen0cd3b642011-10-14 14:58:00 -07002362
Michael Jurka0142d492010-08-25 17:46:15 -07002363 // Update all the pages
2364 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002365
Winson Chung5a808352011-06-27 19:08:49 -07002366 // We must force a measure after we've loaded the pages to update the content width and
2367 // to determine the full scroll width
2368 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2369 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2370
2371 // Set a new page as the current page if necessary
2372 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002373 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002374 }
2375
Michael Jurka0142d492010-08-25 17:46:15 -07002376 // Mark each of the pages as dirty
2377 final int count = getChildCount();
2378 mDirtyPageContent.clear();
2379 for (int i = 0; i < count; ++i) {
2380 mDirtyPageContent.add(true);
2381 }
2382
2383 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002384 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002385 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002386 }
Adam Cohen06559042013-09-29 18:30:56 -07002387 if (isPageMoving()) {
2388 // If the page is moving, then snap it to the final position to ensure we don't get
2389 // stuck between pages
2390 snapToDestination();
2391 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002392 }
Winson Chung007c6982011-06-14 13:27:53 -07002393
Adam Cohen7d30a372013-07-01 17:03:59 -07002394 // Animate the drag view back to the original position
2395 void animateDragViewToOriginalPosition() {
2396 if (mDragView != null) {
2397 AnimatorSet anim = new AnimatorSet();
2398 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2399 anim.playTogether(
2400 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002401 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2402 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2403 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002404 anim.addListener(new AnimatorListenerAdapter() {
2405 @Override
2406 public void onAnimationEnd(Animator animation) {
2407 onPostReorderingAnimationCompleted();
2408 }
2409 });
2410 anim.start();
2411 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002412 }
2413
Adam Cohen7d30a372013-07-01 17:03:59 -07002414 protected void onStartReordering() {
2415 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2416 mTouchState = TOUCH_STATE_REORDERING;
2417 mIsReordering = true;
2418
Adam Cohen7d30a372013-07-01 17:03:59 -07002419 // We must invalidate to trigger a redraw to update the layers such that the drag view
2420 // is always drawn on top
2421 invalidate();
2422 }
2423
2424 private void onPostReorderingAnimationCompleted() {
2425 // Trigger the callback when reordering has settled
2426 --mPostReorderingPreZoomInRemainingAnimationCount;
2427 if (mPostReorderingPreZoomInRunnable != null &&
2428 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2429 mPostReorderingPreZoomInRunnable.run();
2430 mPostReorderingPreZoomInRunnable = null;
2431 }
2432 }
2433
2434 protected void onEndReordering() {
2435 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002436 }
2437
Adam Cohenf358a4b2013-07-23 16:47:31 -07002438 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002439 int dragViewIndex = indexOfChild(v);
2440
2441 if (mTouchState != TOUCH_STATE_REST) return false;
2442
Adam Cohen7d30a372013-07-01 17:03:59 -07002443 mTempVisiblePagesRange[0] = 0;
2444 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002445 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002446 mReorderingStarted = true;
2447
2448 // Check if we are within the reordering range
2449 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002450 dragViewIndex <= mTempVisiblePagesRange[1]) {
2451 // Find the drag view under the pointer
2452 mDragView = getChildAt(dragViewIndex);
2453 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2454 mDragViewBaselineLeft = mDragView.getLeft();
2455 disableFreeScroll(-1);
2456 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002457 return true;
2458 }
2459 return false;
2460 }
2461
2462 boolean isReordering(boolean testTouchState) {
2463 boolean state = mIsReordering;
2464 if (testTouchState) {
2465 state &= (mTouchState == TOUCH_STATE_REORDERING);
2466 }
2467 return state;
2468 }
2469 void endReordering() {
2470 // For simplicity, we call endReordering sometimes even if reordering was never started.
2471 // In that case, we don't want to do anything.
2472 if (!mReorderingStarted) return;
2473 mReorderingStarted = false;
2474
2475 // If we haven't flung-to-delete the current child, then we just animate the drag view
2476 // back into position
2477 final Runnable onCompleteRunnable = new Runnable() {
2478 @Override
2479 public void run() {
2480 onEndReordering();
2481 }
2482 };
2483 if (!mDeferringForDelete) {
2484 mPostReorderingPreZoomInRunnable = new Runnable() {
2485 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002486 onCompleteRunnable.run();
2487 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002488 };
2489 };
2490
2491 mPostReorderingPreZoomInRemainingAnimationCount =
2492 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2493 // Snap to the current page
2494 snapToPage(indexOfChild(mDragView), 0);
2495 // Animate the drag view back to the front position
2496 animateDragViewToOriginalPosition();
2497 } else {
2498 // Handled in post-delete-animation-callbacks
2499 }
2500 }
2501
Adam Cohen7d30a372013-07-01 17:03:59 -07002502 /*
2503 * Flinging to delete - IN PROGRESS
2504 */
2505 private PointF isFlingingToDelete() {
2506 ViewConfiguration config = ViewConfiguration.get(getContext());
2507 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2508
2509 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2510 // Do a quick dot product test to ensure that we are flinging upwards
2511 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2512 mVelocityTracker.getYVelocity());
2513 PointF upVec = new PointF(0f, -1f);
2514 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2515 (vel.length() * upVec.length()));
2516 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2517 return vel;
2518 }
2519 }
2520 return null;
2521 }
2522
2523 /**
2524 * Creates an animation from the current drag view along its current velocity vector.
2525 * For this animation, the alpha runs for a fixed duration and we update the position
2526 * progressively.
2527 */
2528 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2529 private View mDragView;
2530 private PointF mVelocity;
2531 private Rect mFrom;
2532 private long mPrevTime;
2533 private float mFriction;
2534
2535 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2536
2537 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2538 long startTime, float friction) {
2539 mDragView = dragView;
2540 mVelocity = vel;
2541 mFrom = from;
2542 mPrevTime = startTime;
2543 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2544 }
2545
2546 @Override
2547 public void onAnimationUpdate(ValueAnimator animation) {
2548 float t = ((Float) animation.getAnimatedValue()).floatValue();
2549 long curTime = AnimationUtils.currentAnimationTimeMillis();
2550
2551 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2552 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2553
2554 mDragView.setTranslationX(mFrom.left);
2555 mDragView.setTranslationY(mFrom.top);
2556 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2557
2558 mVelocity.x *= mFriction;
2559 mVelocity.y *= mFriction;
2560 mPrevTime = curTime;
2561 }
2562 };
2563
2564 private static final int ANIM_TAG_KEY = 100;
2565
2566 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2567 return new Runnable() {
2568 @Override
2569 public void run() {
2570 int dragViewIndex = indexOfChild(dragView);
2571
2572 // For each of the pages around the drag view, animate them from the previous
2573 // position to the new position in the layout (as a result of the drag view moving
2574 // in the layout)
2575 // NOTE: We can make an assumption here because we have side-bound pages that we
2576 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002577 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002578 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2579 boolean slideFromLeft = (isLastWidgetPage ||
2580 dragViewIndex > mTempVisiblePagesRange[0]);
2581
2582 // Setup the scroll to the correct page before we swap the views
2583 if (slideFromLeft) {
2584 snapToPageImmediately(dragViewIndex - 1);
2585 }
2586
2587 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2588 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2589 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2590 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2591 ArrayList<Animator> animations = new ArrayList<Animator>();
2592 for (int i = lowerIndex; i <= upperIndex; ++i) {
2593 View v = getChildAt(i);
2594 // dragViewIndex < pageUnderPointIndex, so after we remove the
2595 // drag view all subsequent views to pageUnderPointIndex will
2596 // shift down.
2597 int oldX = 0;
2598 int newX = 0;
2599 if (slideFromLeft) {
2600 if (i == 0) {
2601 // Simulate the page being offscreen with the page spacing
2602 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
Adam Cohen3b185e22013-10-29 14:45:58 -07002603 - mPageSpacing;
Adam Cohen7d30a372013-07-01 17:03:59 -07002604 } else {
2605 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2606 }
2607 newX = getViewportOffsetX() + getChildOffset(i);
2608 } else {
2609 oldX = getChildOffset(i) - getChildOffset(i - 1);
2610 newX = 0;
2611 }
2612
2613 // Animate the view translation from its old position to its new
2614 // position
2615 AnimatorSet anim = (AnimatorSet) v.getTag();
2616 if (anim != null) {
2617 anim.cancel();
2618 }
2619
2620 // Note: Hacky, but we want to skip any optimizations to not draw completely
2621 // hidden views
2622 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2623 v.setTranslationX(oldX - newX);
2624 anim = new AnimatorSet();
2625 anim.playTogether(
2626 ObjectAnimator.ofFloat(v, "translationX", 0f),
2627 ObjectAnimator.ofFloat(v, "alpha", 1f));
2628 animations.add(anim);
2629 v.setTag(ANIM_TAG_KEY, anim);
2630 }
2631
2632 AnimatorSet slideAnimations = new AnimatorSet();
2633 slideAnimations.playTogether(animations);
2634 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2635 slideAnimations.addListener(new AnimatorListenerAdapter() {
2636 @Override
2637 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002638 mDeferringForDelete = false;
2639 onEndReordering();
2640 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002641 }
2642 });
2643 slideAnimations.start();
2644
2645 removeView(dragView);
2646 onRemoveView(dragView, true);
2647 }
2648 };
2649 }
2650
2651 public void onFlingToDelete(PointF vel) {
2652 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2653
2654 // NOTE: Because it takes time for the first frame of animation to actually be
2655 // called and we expect the animation to be a continuation of the fling, we have
2656 // to account for the time that has elapsed since the fling finished. And since
2657 // we don't have a startDelay, we will always get call to update when we call
2658 // start() (which we want to ignore).
2659 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2660 private int mCount = -1;
2661 private long mStartTime;
2662 private float mOffset;
2663 /* Anonymous inner class ctor */ {
2664 mStartTime = startTime;
2665 }
2666
2667 @Override
2668 public float getInterpolation(float t) {
2669 if (mCount < 0) {
2670 mCount++;
2671 } else if (mCount == 0) {
2672 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2673 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2674 mCount++;
2675 }
2676 return Math.min(1f, mOffset + t);
2677 }
2678 };
2679
2680 final Rect from = new Rect();
2681 final View dragView = mDragView;
2682 from.left = (int) dragView.getTranslationX();
2683 from.top = (int) dragView.getTranslationY();
2684 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2685 from, startTime, FLING_TO_DELETE_FRICTION);
2686
2687 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2688
2689 // Create and start the animation
2690 ValueAnimator mDropAnim = new ValueAnimator();
2691 mDropAnim.setInterpolator(tInterpolator);
2692 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2693 mDropAnim.setFloatValues(0f, 1f);
2694 mDropAnim.addUpdateListener(updateCb);
2695 mDropAnim.addListener(new AnimatorListenerAdapter() {
2696 public void onAnimationEnd(Animator animation) {
2697 onAnimationEndRunnable.run();
2698 }
2699 });
2700 mDropAnim.start();
2701 mDeferringForDelete = true;
2702 }
2703
2704 /* Drag to delete */
2705 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2706 if (mDeleteDropTarget != null) {
2707 mAltTmpRect.set(0, 0, 0, 0);
2708 View parent = (View) mDeleteDropTarget.getParent();
2709 if (parent != null) {
2710 parent.getGlobalVisibleRect(mAltTmpRect);
2711 }
2712 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2713 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2714 return mTmpRect.contains(x, y);
2715 }
2716 return false;
2717 }
2718
2719 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2720
2721 private void onDropToDelete() {
2722 final View dragView = mDragView;
2723
2724 final float toScale = 0f;
2725 final float toAlpha = 0f;
2726
2727 // Create and start the complex animation
2728 ArrayList<Animator> animations = new ArrayList<Animator>();
2729 AnimatorSet motionAnim = new AnimatorSet();
2730 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2731 motionAnim.playTogether(
2732 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2733 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2734 animations.add(motionAnim);
2735
2736 AnimatorSet alphaAnim = new AnimatorSet();
2737 alphaAnim.setInterpolator(new LinearInterpolator());
2738 alphaAnim.playTogether(
2739 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2740 animations.add(alphaAnim);
2741
2742 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2743
2744 AnimatorSet anim = new AnimatorSet();
2745 anim.playTogether(animations);
2746 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2747 anim.addListener(new AnimatorListenerAdapter() {
2748 public void onAnimationEnd(Animator animation) {
2749 onAnimationEndRunnable.run();
2750 }
2751 });
2752 anim.start();
2753
2754 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002755 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002756
2757 /* Accessibility */
2758 @Override
2759 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2760 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002761 info.setScrollable(getPageCount() > 1);
2762 if (getCurrentPage() < getPageCount() - 1) {
2763 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2764 }
2765 if (getCurrentPage() > 0) {
2766 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2767 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002768 }
2769
2770 @Override
Alan Viverette254139a2013-10-08 13:13:46 -07002771 public void sendAccessibilityEvent(int eventType) {
2772 // Don't let the view send real scroll events.
2773 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2774 super.sendAccessibilityEvent(eventType);
2775 }
2776 }
2777
2778 @Override
Winson Chung6a0f57d2011-06-29 20:10:49 -07002779 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2780 super.onInitializeAccessibilityEvent(event);
2781 event.setScrollable(true);
Winson Chung6a0f57d2011-06-29 20:10:49 -07002782 }
2783
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002784 @Override
2785 public boolean performAccessibilityAction(int action, Bundle arguments) {
2786 if (super.performAccessibilityAction(action, arguments)) {
2787 return true;
2788 }
2789 switch (action) {
2790 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2791 if (getCurrentPage() < getPageCount() - 1) {
2792 scrollRight();
2793 return true;
2794 }
2795 } break;
2796 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2797 if (getCurrentPage() > 0) {
2798 scrollLeft();
2799 return true;
2800 }
2801 } break;
2802 }
2803 return false;
2804 }
2805
Adam Cohen0ffac432013-07-10 11:19:26 -07002806 protected String getCurrentPageDescription() {
2807 return String.format(getContext().getString(R.string.default_scroll_format),
2808 getNextPage() + 1, getChildCount());
2809 }
2810
Winson Chungd11265e2011-08-30 13:37:23 -07002811 @Override
2812 public boolean onHoverEvent(android.view.MotionEvent event) {
2813 return true;
2814 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002815}