blob: 21826806ad8d18b539798b21b3cc5e41e954e4e9 [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 Cohenf358a4b2013-07-23 16:47:31 -0700100 private boolean mFreeScroll = false;
101 private int mFreeScrollMinScrollX = -1;
102 private int mFreeScrollMaxScrollX = -1;
103
Winson Chung8aad6102012-05-11 16:27:49 -0700104 static final int AUTOMATIC_PAGE_SPACING = -1;
105
Adam Cohen265b9a62011-12-07 14:37:18 -0800106 protected int mFlingThresholdVelocity;
107 protected int mMinFlingVelocity;
108 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700109
Adam Cohenb5ba0972011-09-07 18:02:31 -0700110 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected float mSmoothingTime;
112 protected float mTouchX;
113
114 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700115 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700116
117 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700118 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700119 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700120
Michael Jurka0142d492010-08-25 17:46:15 -0700121 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800122 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700123 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700124 private VelocityTracker mVelocityTracker;
125
Adam Cohen7d30a372013-07-01 17:03:59 -0700126 private float mParentDownMotionX;
127 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700128 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700129 private float mDownMotionY;
130 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700131 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800132 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800133 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800134 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800135 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700136 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700137
Adam Cohendbdff6b2013-09-18 19:09:15 -0700138 private boolean mCancelTap;
139
Adam Cohenedb40762013-07-18 16:45:45 -0700140 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700141
Michael Jurka0142d492010-08-25 17:46:15 -0700142 protected final static int TOUCH_STATE_REST = 0;
143 protected final static int TOUCH_STATE_SCROLLING = 1;
144 protected final static int TOUCH_STATE_PREV_PAGE = 2;
145 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700146 protected final static int TOUCH_STATE_REORDERING = 4;
147
Adam Cohene45440e2010-10-14 18:33:38 -0700148 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700149
Michael Jurka0142d492010-08-25 17:46:15 -0700150 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700151 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700152
Michael Jurka0142d492010-08-25 17:46:15 -0700153 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700154
Michael Jurka7426c422010-11-11 15:23:47 -0800155 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700156 private int mPagingTouchSlop;
157 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700158 protected int mPageSpacing;
159 protected int mPageLayoutPaddingTop;
160 protected int mPageLayoutPaddingBottom;
161 protected int mPageLayoutPaddingLeft;
162 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700163 protected int mPageLayoutWidthGap;
164 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700165 protected int mCellCountX = 0;
166 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700167 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800168 protected boolean mAllowOverScroll = true;
169 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800170 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700171 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700172
Michael Jurka8b805b12012-04-18 14:23:14 -0700173 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800174 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
175 // the screens from continuing to translate beyond the normal bounds.
176 protected int mOverScrollX;
177
Michael Jurka5f1c5092010-09-03 14:15:02 -0700178 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700179
Michael Jurka5f1c5092010-09-03 14:15:02 -0700180 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700181
Winson Chung86f77532010-08-24 11:08:22 -0700182 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700183
Michael Jurkae326f182011-11-21 14:05:46 -0800184 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700185
Michael Jurka0142d492010-08-25 17:46:15 -0700186 // If true, syncPages and syncPageItems will be called to refresh pages
187 protected boolean mContentIsRefreshable = true;
188
189 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700190 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700191
192 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
193 // to switch to a new page
194 protected boolean mUsePagingTouchSlop = true;
195
Michael Jurka8b805b12012-04-18 14:23:14 -0700196 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700197 // (SmoothPagedView does this)
198 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700199 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700200
Patrick Dubroy1262e362010-10-06 15:49:50 -0700201 protected boolean mIsPageMoving = false;
202
Winson Chungf0ea4d32011-06-06 14:27:16 -0700203 // All syncs and layout passes are deferred until data is ready.
204 protected boolean mIsDataReady = false;
205
Adam Cohen7d30a372013-07-01 17:03:59 -0700206 protected boolean mAllowLongPress = true;
207
Winson Chungd2be3812013-07-16 11:11:32 -0700208 // Page Indicator
209 private int mPageIndicatorViewId;
210 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700211 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700212
Adam Cohen7d30a372013-07-01 17:03:59 -0700213 // The viewport whether the pages are to be contained (the actual view may be larger than the
214 // viewport)
215 private Rect mViewport = new Rect();
216
217 // Reordering
218 // We use the min scale to determine how much to expand the actually PagedView measured
219 // dimensions such that when we are zoomed out, the view is not clipped
220 private int REORDERING_DROP_REPOSITION_DURATION = 200;
221 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
222 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700223 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700224 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700225 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700226 protected View mDragView;
227 protected AnimatorSet mZoomInOutAnim;
228 private Runnable mSidePageHoverRunnable;
229 private int mSidePageHoverIndex = -1;
230 // This variable's scope is only for the duration of startReordering() and endReordering()
231 private boolean mReorderingStarted = false;
232 // This variable's scope is for the duration of startReordering() and after the zoomIn()
233 // animation after endReordering()
234 private boolean mIsReordering;
235 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
236 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
237 private int mPostReorderingPreZoomInRemainingAnimationCount;
238 private Runnable mPostReorderingPreZoomInRunnable;
239
Adam Cohen7d30a372013-07-01 17:03:59 -0700240 // Convenience/caching
241 private Matrix mTmpInvMatrix = new Matrix();
242 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700243 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700244 private Rect mTmpRect = new Rect();
245 private Rect mAltTmpRect = new Rect();
246
247 // Fling to delete
248 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
249 private float FLING_TO_DELETE_FRICTION = 0.035f;
250 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
251 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
252 protected int mFlingToDeleteThresholdVelocity = -1400;
253 // Drag to delete
254 private boolean mDeferringForDelete = false;
255 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
256 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
257
258 // Drop to delete
259 private View mDeleteDropTarget;
260
261 private boolean mAutoComputePageSpacing = false;
262 private boolean mRecomputePageSpacing = false;
263
264 // Bouncer
265 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700266
John Spurlock77e1f472013-09-11 10:09:51 -0400267 protected final Rect mInsets = new Rect();
268
Michael Jurkafe0ace32013-10-03 01:05:14 -0700269 protected int mFirstChildLeft;
270
Winson Chung86f77532010-08-24 11:08:22 -0700271 public interface PageSwitchListener {
272 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700273 }
274
Winson Chung321e9ee2010-08-09 13:37:56 -0700275 public PagedView(Context context) {
276 this(context, null);
277 }
278
279 public PagedView(Context context, AttributeSet attrs) {
280 this(context, attrs, 0);
281 }
282
283 public PagedView(Context context, AttributeSet attrs, int defStyle) {
284 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700285
Adam Cohen9c4949e2010-10-05 12:27:22 -0700286 TypedArray a = context.obtainStyledAttributes(attrs,
287 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800288 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700289 if (mPageSpacing < 0) {
290 mAutoComputePageSpacing = mRecomputePageSpacing = true;
291 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800293 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700294 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800295 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700296 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800297 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700298 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800299 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700300 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700301 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700302 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700303 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700304 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700305 a.recycle();
306
Winson Chung321e9ee2010-08-09 13:37:56 -0700307 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700308 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700309 }
310
311 /**
312 * Initializes various states for this workspace.
313 */
Michael Jurka0142d492010-08-25 17:46:15 -0700314 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700315 mDirtyPageContent = new ArrayList<Boolean>();
316 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800317 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700318 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700319 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700320
321 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700322 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700323 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
324 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700325 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800326
Adam Cohen7d30a372013-07-01 17:03:59 -0700327 // Scale the fling-to-delete threshold by the density
328 mFlingToDeleteThresholdVelocity =
329 (int) (mFlingToDeleteThresholdVelocity * mDensity);
330
Adam Cohen265b9a62011-12-07 14:37:18 -0800331 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
332 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
333 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700334 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700335 }
336
Winson Chungd2be3812013-07-16 11:11:32 -0700337 protected void onAttachedToWindow() {
Adam Cohen53805212013-10-01 10:39:23 -0700338 super.onAttachedToWindow();
339
Winson Chungd2be3812013-07-16 11:11:32 -0700340 // Hook up the page indicator
341 ViewGroup parent = (ViewGroup) getParent();
342 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
343 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700344 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700345
Winson Chung7819a562013-09-19 15:55:45 -0700346 ArrayList<PageIndicator.PageMarkerResources> markers =
347 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700348 for (int i = 0; i < getChildCount(); ++i) {
349 markers.add(getPageIndicatorMarker(i));
350 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700351
Winson Chungc58497e2013-09-03 17:48:37 -0700352 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohen53805212013-10-01 10:39:23 -0700353 mPageIndicator.setOnClickListener(getPageIndicatorClickListener());
354 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);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800512 mScroller.forceFinished(true);
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
517 * ends, {@link #resumeScrolling()} should be called, along with
518 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
519 */
520 void pauseScrolling() {
521 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700522 }
523
524 /**
525 * Enables scrolling again.
526 * @see #pauseScrolling()
527 */
528 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700529 }
530 /**
Winson Chung86f77532010-08-24 11:08:22 -0700531 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700532 */
Winson Chung86f77532010-08-24 11:08:22 -0700533 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800534 if (!mScroller.isFinished()) {
535 mScroller.abortAnimation();
Adam Cohen97d53112013-10-01 11:07:24 -0700536 // We need to clean up the next page here to avoid computeScrollHelper from
537 // updating current page on the pass.
538 mNextPage = INVALID_PAGE;
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800539 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800540 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
541 // the default
542 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800543 return;
544 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700545
Adam Cohene61a9a22013-06-11 15:45:31 -0700546 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700547 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700548 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700549 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800550 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700551 }
552
Winson Chung8c87cd82013-07-23 16:20:10 -0700553 /**
554 * The restore page will be set in place of the current page at the next (likely first)
555 * layout.
556 */
557 void setRestorePage(int restorePage) {
558 mRestorePage = restorePage;
559 }
560
Michael Jurka0142d492010-08-25 17:46:15 -0700561 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700562 if (mPageSwitchListener != null) {
563 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700564 }
Winson Chungd2be3812013-07-16 11:11:32 -0700565
566 // Update the page indicator (when we aren't reordering)
567 if (mPageIndicator != null && !isReordering(false)) {
568 mPageIndicator.setActiveMarker(getNextPage());
569 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700570 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800571 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700572 if (!mIsPageMoving) {
573 mIsPageMoving = true;
574 onPageBeginMoving();
575 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700576 }
577
Michael Jurkace7e05f2011-02-01 22:02:35 -0800578 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700579 if (mIsPageMoving) {
580 mIsPageMoving = false;
581 onPageEndMoving();
582 }
Michael Jurka0142d492010-08-25 17:46:15 -0700583 }
584
Adam Cohen26976d92011-03-22 15:33:33 -0700585 protected boolean isPageMoving() {
586 return mIsPageMoving;
587 }
588
Michael Jurka0142d492010-08-25 17:46:15 -0700589 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700590 protected void onPageBeginMoving() {
591 }
592
593 // a method that subclasses can override to add behavior
594 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700595 }
596
Winson Chung321e9ee2010-08-09 13:37:56 -0700597 /**
Winson Chung86f77532010-08-24 11:08:22 -0700598 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700599 *
600 * @param l The listener used to respond to long clicks.
601 */
602 @Override
603 public void setOnLongClickListener(OnLongClickListener l) {
604 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700605 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700606 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700607 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700608 }
Adam Cohen1697b792013-09-17 19:08:21 -0700609 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700610 }
611
612 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800613 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700614 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800615 }
616
617 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700618 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700619 // In free scroll mode, we clamp the scrollX
620 if (mFreeScroll) {
621 x = Math.min(x, mFreeScrollMaxScrollX);
622 x = Math.max(x, mFreeScrollMinScrollX);
623 }
624
Adam Cohen0ffac432013-07-10 11:19:26 -0700625 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800626 mUnboundedScrollX = x;
627
Adam Cohen0ffac432013-07-10 11:19:26 -0700628 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
629 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
630 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800631 super.scrollTo(0, y);
632 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700633 if (isRtl) {
634 overScroll(x - mMaxScrollX);
635 } else {
636 overScroll(x);
637 }
Adam Cohen68d73932010-11-15 10:50:58 -0800638 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700639 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800640 super.scrollTo(mMaxScrollX, y);
641 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700642 if (isRtl) {
643 overScroll(x);
644 } else {
645 overScroll(x - mMaxScrollX);
646 }
Adam Cohen68d73932010-11-15 10:50:58 -0800647 }
648 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800649 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800650 super.scrollTo(x, y);
651 }
652
Michael Jurka0142d492010-08-25 17:46:15 -0700653 mTouchX = x;
654 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700655
656 // Update the last motion events when scrolling
657 if (isReordering(true)) {
658 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
659 mLastMotionX = p[0];
660 mLastMotionY = p[1];
661 updateDragViewTranslationDuringDrag();
662 }
Michael Jurka0142d492010-08-25 17:46:15 -0700663 }
664
Adam Cohen53805212013-10-01 10:39:23 -0700665 private void sendScrollAccessibilityEvent() {
666 AccessibilityManager am =
667 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
668 if (am.isEnabled()) {
669 AccessibilityEvent ev =
670 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
Adam Cohen53805212013-10-01 10:39:23 -0700671 ev.setItemCount(getChildCount());
672 ev.setFromIndex(mCurrentPage);
Adam Cohen53805212013-10-01 10:39:23 -0700673
Alan Viverette254139a2013-10-08 13:13:46 -0700674 final int action;
Adam Cohen53805212013-10-01 10:39:23 -0700675 if (getNextPage() >= mCurrentPage) {
676 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD;
677 } else {
678 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
679 }
680
681 ev.setAction(action);
682 sendAccessibilityEventUnchecked(ev);
683 }
684 }
685
Michael Jurka0142d492010-08-25 17:46:15 -0700686 // we moved this functionality to a helper function so SmoothPagedView can reuse it
687 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700688 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700689 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700690 if (getScrollX() != mScroller.getCurrX()
691 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700692 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700693 float scaleX = mFreeScroll ? getScaleX() : 1f;
694 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
695 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700696 }
Michael Jurka0142d492010-08-25 17:46:15 -0700697 invalidate();
698 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700699 } else if (mNextPage != INVALID_PAGE) {
Adam Cohen53805212013-10-01 10:39:23 -0700700 sendScrollAccessibilityEvent();
701
Winson Chung86f77532010-08-24 11:08:22 -0700702 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700703 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700704 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700705
Winson Chung9c0565f2013-07-19 13:49:06 -0700706 // Load the associated pages if necessary
707 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
708 loadAssociatedPages(mCurrentPage);
709 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
710 }
711
Adam Cohen73aa9752010-11-24 16:26:58 -0800712 // We don't want to trigger a page end moving unless the page has settled
713 // and the user has stopped scrolling
714 if (mTouchState == TOUCH_STATE_REST) {
715 pageEndMoving();
716 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700717
Adam Cohen7d30a372013-07-01 17:03:59 -0700718 onPostReorderingAnimationCompleted();
Adam Cohen53805212013-10-01 10:39:23 -0700719 AccessibilityManager am = (AccessibilityManager)
Adam Cohen0ffac432013-07-10 11:19:26 -0700720 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
Adam Cohen53805212013-10-01 10:39:23 -0700721 if (am.isEnabled()) {
722 // Notify the user when the page changes
723 announceForAccessibility(getCurrentPageDescription());
Adam Cohen0ffac432013-07-10 11:19:26 -0700724 }
Michael Jurka0142d492010-08-25 17:46:15 -0700725 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700726 }
Michael Jurka0142d492010-08-25 17:46:15 -0700727 return false;
728 }
729
730 @Override
731 public void computeScroll() {
732 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700733 }
734
Adam Cohen7d30a372013-07-01 17:03:59 -0700735 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
736 return mTopAlignPageWhenShrinkingForBouncer;
737 }
738
Adam Cohen96d30a12013-07-16 18:13:21 -0700739 public static class LayoutParams extends ViewGroup.LayoutParams {
740 public boolean isFullScreenPage = false;
741
742 /**
743 * {@inheritDoc}
744 */
745 public LayoutParams(int width, int height) {
746 super(width, height);
747 }
748
749 public LayoutParams(ViewGroup.LayoutParams source) {
750 super(source);
751 }
752 }
753
754 protected LayoutParams generateDefaultLayoutParams() {
755 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
756 }
757
Adam Cohenedb40762013-07-18 16:45:45 -0700758 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700759 LayoutParams lp = generateDefaultLayoutParams();
760 lp.isFullScreenPage = true;
761 super.addView(page, 0, lp);
762 }
763
Adam Cohen410f3cd2013-09-22 12:09:32 -0700764 public int getNormalChildHeight() {
765 return mNormalChildHeight;
766 }
767
Winson Chung321e9ee2010-08-09 13:37:56 -0700768 @Override
769 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700770 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700771 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
772 return;
773 }
774
Adam Cohen7d30a372013-07-01 17:03:59 -0700775 // We measure the dimensions of the PagedView to be larger than the pages so that when we
776 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700777 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
778 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
779 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700780 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700781 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
782 // viewport, we can be at most one and a half screens offset once we scale down
783 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700784 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700785
Winson Chungc58497e2013-09-03 17:48:37 -0700786 int parentWidthSize, parentHeightSize;
787 int scaledWidthSize, scaledHeightSize;
788 if (mUseMinScale) {
789 parentWidthSize = (int) (1.5f * maxSize);
790 parentHeightSize = maxSize;
791 scaledWidthSize = (int) (parentWidthSize / mMinScale);
792 scaledHeightSize = (int) (parentHeightSize / mMinScale);
793 } else {
794 scaledWidthSize = widthSize;
795 scaledHeightSize = heightSize;
796 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700797 mViewport.set(0, 0, widthSize, heightSize);
798
799 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
800 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
801 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700802 }
803
Winson Chung8aad6102012-05-11 16:27:49 -0700804 // Return early if we aren't given a proper dimension
805 if (widthSize <= 0 || heightSize <= 0) {
806 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
807 return;
808 }
809
Adam Lesinski6b879f02010-11-04 16:15:23 -0700810 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
811 * of the All apps view on XLarge displays to not take up more space then it needs. Width
812 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
813 * each page to have the same width.
814 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700815 final int verticalPadding = getPaddingTop() + getPaddingBottom();
816 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700817
818 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700819 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700820 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700821 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
822 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
823 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
824 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700825 final int childCount = getChildCount();
826 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700827 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700828 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700829 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
830
831 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700832 int childHeightMode;
833 int childWidth;
834 int childHeight;
835
836 if (!lp.isFullScreenPage) {
837 if (lp.width == LayoutParams.WRAP_CONTENT) {
838 childWidthMode = MeasureSpec.AT_MOST;
839 } else {
840 childWidthMode = MeasureSpec.EXACTLY;
841 }
842
843 if (lp.height == LayoutParams.WRAP_CONTENT) {
844 childHeightMode = MeasureSpec.AT_MOST;
845 } else {
846 childHeightMode = MeasureSpec.EXACTLY;
847 }
848
849 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400850 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700851 mNormalChildHeight = childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700852
Michael Jurka5f1c5092010-09-03 14:15:02 -0700853 } else {
854 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700855 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700856
Winson Chungc58497e2013-09-03 17:48:37 -0700857 if (mUseMinScale) {
858 childWidth = getViewportWidth();
859 childHeight = getViewportHeight();
860 } else {
861 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
862 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
863 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700864 }
865
866 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700867 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
868 final int childHeightMeasureSpec =
869 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700870 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700871 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700872 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700873
Winson Chunga128a7b2012-04-30 15:23:15 -0700874 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700875 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700876 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700877 // The gap between pages in the PagedView should be equal to the gap from the page
878 // to the edge of the screen (so it is not visible in the current screen). To
879 // account for unequal padding on each side of the paged view, we take the maximum
880 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700881 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700882 int spacing = Math.max(offset, widthSize - offset -
883 getChildAt(0).getMeasuredWidth());
884 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700885 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700886 }
887 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700888 }
889
Adam Cohen60b07122011-11-14 17:26:06 -0800890 public void setPageSpacing(int pageSpacing) {
891 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700892 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800893 }
894
Michael Jurkafe0ace32013-10-03 01:05:14 -0700895 protected int getFirstChildLeft() {
896 return mFirstChildLeft;
897 }
898
Winson Chung321e9ee2010-08-09 13:37:56 -0700899 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700900 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700901 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700902 return;
903 }
904
Winson Chung785d2eb2011-04-14 16:08:02 -0700905 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700906 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700907
Adam Cohenedb40762013-07-18 16:45:45 -0700908 int screenWidth = getViewportWidth();
909
Adam Cohen7d30a372013-07-01 17:03:59 -0700910 int offsetX = getViewportOffsetX();
911 int offsetY = getViewportOffsetY();
912
913 // Update the viewport offsets
914 mViewport.offset(offsetX, offsetY);
915
Adam Cohen0ffac432013-07-10 11:19:26 -0700916 final boolean isRtl = isLayoutRtl();
917
918 final int startIndex = isRtl ? childCount - 1 : 0;
919 final int endIndex = isRtl ? -1 : childCount;
920 final int delta = isRtl ? -1 : 1;
921
Adam Cohen7d30a372013-07-01 17:03:59 -0700922 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700923
Michael Jurkafe0ace32013-10-03 01:05:14 -0700924 int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700925 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
926 mPageScrolls = new int[getChildCount()];
927 }
928
Adam Cohen0ffac432013-07-10 11:19:26 -0700929 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700930 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700931 LayoutParams lp = (LayoutParams) child.getLayoutParams();
932 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700933 if (lp.isFullScreenPage) {
934 childTop = offsetY;
935 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400936 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700937 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400938 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700939 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700940 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700941
Winson Chung321e9ee2010-08-09 13:37:56 -0700942 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700943 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700944 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800945
Winson Chung785d2eb2011-04-14 16:08:02 -0700946 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700947 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800948 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700949
950 // We assume the left and right padding are equal, and hence center the pages
951 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700952 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700953 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
954
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700955 if (i != endIndex - delta) {
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700956 childLeft += childWidth + scrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700957 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700958 childLeft += nextScrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700959 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700960 }
961 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700962
963 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
964 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800965 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700966 setHorizontalScrollBarEnabled(true);
967 mFirstLayout = false;
968 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700969
970 if (childCount > 0) {
971 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700972 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700973 } else {
974 mMaxScrollX = 0;
975 }
976
977 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
978 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700979 if (mRestorePage > -1) {
980 setCurrentPage(mRestorePage);
981 mRestorePage = -1;
982 } else {
983 setCurrentPage(getNextPage());
984 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700985 }
986 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700987
988 if (isReordering(true)) {
989 updateDragViewTranslationDuringDrag();
990 }
Winson Chunge3193b92010-09-10 11:44:42 -0700991 }
992
Adam Cohenf34bab52010-09-30 14:11:56 -0700993 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700994 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
995
996 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700997 for (int i = 0; i < getChildCount(); i++) {
998 View child = getChildAt(i);
999 if (child != null) {
1000 float scrollProgress = getScrollProgress(screenCenter, child, i);
1001 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -08001002 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -07001003 }
1004 }
1005 invalidate();
1006 }
Adam Cohenf34bab52010-09-30 14:11:56 -07001007 }
1008
Winson Chungc58497e2013-09-03 17:48:37 -07001009 protected void enablePagedViewAnimations() {
1010 mAllowPagedViewAnimations = true;
1011
1012 }
1013 protected void disablePagedViewAnimations() {
1014 mAllowPagedViewAnimations = false;
1015 }
1016
Winson Chunge3193b92010-09-10 11:44:42 -07001017 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -07001018 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -07001019 // Update the page indicator, we don't update the page indicator as we
1020 // add/remove pages
1021 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -07001022 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -07001023 mPageIndicator.addMarker(pageIndex,
1024 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -07001025 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001026 }
1027
Adam Cohen2591f6a2011-10-25 14:36:40 -07001028 // This ensures that when children are added, they get the correct transforms / alphas
1029 // in accordance with any scroll effects.
1030 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -07001031 mRecomputePageSpacing = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001032 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001033 invalidate();
1034 }
1035
Michael Jurka8b805b12012-04-18 14:23:14 -07001036 @Override
1037 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001038 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001039 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001040 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001041 }
1042
Winson Chungd2be3812013-07-16 11:11:32 -07001043 private void removeMarkerForView(int index) {
1044 // Update the page indicator, we don't update the page indicator as we
1045 // add/remove pages
1046 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001047 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001048 }
1049 }
1050
1051 @Override
1052 public void removeView(View v) {
1053 // XXX: We should find a better way to hook into this before the view
1054 // gets removed form its parent...
1055 removeMarkerForView(indexOfChild(v));
1056 super.removeView(v);
1057 }
1058 @Override
1059 public void removeViewInLayout(View v) {
1060 // XXX: We should find a better way to hook into this before the view
1061 // gets removed form its parent...
1062 removeMarkerForView(indexOfChild(v));
1063 super.removeViewInLayout(v);
1064 }
1065 @Override
1066 public void removeViewAt(int index) {
1067 // XXX: We should find a better way to hook into this before the view
1068 // gets removed form its parent...
1069 removeViewAt(index);
1070 super.removeViewAt(index);
1071 }
1072 @Override
1073 public void removeAllViewsInLayout() {
1074 // Update the page indicator, we don't update the page indicator as we
1075 // add/remove pages
1076 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001077 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001078 }
1079
1080 super.removeAllViewsInLayout();
1081 }
1082
Adam Cohen73894962011-10-31 13:17:17 -07001083 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001084 if (index < 0 || index > getChildCount() - 1) return 0;
1085
Adam Cohenf698c6e2013-07-17 18:44:25 -07001086 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001087
Adam Cohenf698c6e2013-07-17 18:44:25 -07001088 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001089 }
1090
Adam Cohenf358a4b2013-07-23 16:47:31 -07001091 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001092 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001093 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001094 }
1095
Michael Jurkadde558b2011-11-09 22:09:06 -08001096 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001097 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001098 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001099
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001100 range[0] = -1;
1101 range[1] = -1;
1102
Michael Jurkac4fb9172010-09-02 17:19:20 -07001103 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001104 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001105 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001106
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001107 int count = getChildCount();
1108 for (int i = 0; i < count; i++) {
1109 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001110
Winson Chungc9ca2982013-07-19 12:07:38 -07001111 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001112 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001113 if (mTmpIntPoint[0] > viewportWidth) {
1114 if (range[0] == -1) {
1115 continue;
1116 } else {
1117 break;
1118 }
1119 }
1120
Adam Cohen6a678da2013-09-24 10:58:01 -07001121 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001122 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1123 if (mTmpIntPoint[0] < 0) {
1124 if (range[0] == -1) {
1125 continue;
1126 } else {
1127 break;
1128 }
1129 }
1130 curScreen = i;
1131 if (range[0] < 0) {
1132 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001133 }
1134 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001135
1136 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001137 } else {
1138 range[0] = -1;
1139 range[1] = -1;
1140 }
1141 }
1142
Michael Jurka920d7f42012-05-14 16:29:55 -07001143 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001144 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001145 }
1146
Michael Jurkadde558b2011-11-09 22:09:06 -08001147 @Override
1148 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001149 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001150 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1151 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001152 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001153
1154 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001155 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1156 // set it for the next frame
1157 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001158 screenScrolled(screenCenter);
1159 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001160 }
1161
1162 // Find out which screens are visible; as an optimization we only call draw on them
1163 final int pageCount = getChildCount();
1164 if (pageCount > 0) {
1165 getVisiblePages(mTempVisiblePagesRange);
1166 final int leftScreen = mTempVisiblePagesRange[0];
1167 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001168 if (leftScreen != -1 && rightScreen != -1) {
1169 final long drawingTime = getDrawingTime();
1170 // Clip to the bounds
1171 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001172 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1173 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001174
Adam Cohen7d30a372013-07-01 17:03:59 -07001175 // Draw all the children, leaving the drag view for last
1176 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001177 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001178 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001179 if (mForceDrawAllChildrenNextFrame ||
1180 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001181 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001182 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001183 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001184 // Draw the drag view on top (if there is one)
1185 if (mDragView != null) {
1186 drawChild(canvas, mDragView, drawingTime);
1187 }
1188
Michael Jurka5e368ff2012-05-14 23:13:15 -07001189 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001190 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001191 }
Michael Jurka0142d492010-08-25 17:46:15 -07001192 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001193 }
1194
1195 @Override
1196 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001197 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001198 if (page != mCurrentPage || !mScroller.isFinished()) {
1199 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001200 return true;
1201 }
1202 return false;
1203 }
1204
1205 @Override
1206 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001207 int focusablePage;
1208 if (mNextPage != INVALID_PAGE) {
1209 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001210 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001211 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001212 }
Winson Chung86f77532010-08-24 11:08:22 -07001213 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001214 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001215 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001216 }
1217 return false;
1218 }
1219
1220 @Override
1221 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001222 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001223 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001224 if (getCurrentPage() > 0) {
1225 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001226 return true;
1227 }
1228 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001229 if (getCurrentPage() < getPageCount() - 1) {
1230 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001231 return true;
1232 }
1233 }
1234 return super.dispatchUnhandledMove(focused, direction);
1235 }
1236
1237 @Override
1238 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001239 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001240 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001241 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001242 }
1243 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001244 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001245 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001246 }
1247 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001248 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001249 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001250 }
1251 }
1252 }
1253
1254 /**
1255 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001256 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001257 *
Winson Chung86f77532010-08-24 11:08:22 -07001258 * This happens when live folders requery, and if they're off page, they
1259 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001260 */
1261 @Override
1262 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001263 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001264 View v = focused;
1265 while (true) {
1266 if (v == current) {
1267 super.focusableViewAvailable(focused);
1268 return;
1269 }
1270 if (v == this) {
1271 return;
1272 }
1273 ViewParent parent = v.getParent();
1274 if (parent instanceof View) {
1275 v = (View)v.getParent();
1276 } else {
1277 return;
1278 }
1279 }
1280 }
1281
1282 /**
1283 * {@inheritDoc}
1284 */
1285 @Override
1286 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1287 if (disallowIntercept) {
1288 // We need to make sure to cancel our long press if
1289 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001290 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001291 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001292 }
1293 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1294 }
1295
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001296 /**
1297 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1298 */
1299 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001300 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001301 if (isLayoutRtl()) {
1302 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001303 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001304 }
Adam Cohenedb40762013-07-18 16:45:45 -07001305 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001306 }
1307
1308 /**
1309 * Return true if a tap at (x, y) should trigger a flip to the next page.
1310 */
1311 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001312 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001313 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001314 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001315 }
1316 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001317 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001318 }
Winson Chung52aee602013-01-30 12:01:02 -08001319
Adam Cohen7d30a372013-07-01 17:03:59 -07001320 /** Returns whether x and y originated within the buffered viewport */
1321 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1322 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1323 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1324 return mTmpRect.contains(x, y);
1325 }
1326
Winson Chung321e9ee2010-08-09 13:37:56 -07001327 @Override
1328 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001329 if (DISABLE_TOUCH_INTERACTION) {
1330 return false;
1331 }
1332
Winson Chung321e9ee2010-08-09 13:37:56 -07001333 /*
1334 * This method JUST determines whether we want to intercept the motion.
1335 * If we return true, onTouchEvent will be called and we do the actual
1336 * scrolling there.
1337 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001338 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001339
Winson Chung45e1d6e2010-11-09 17:19:49 -08001340 // Skip touch handling if there are no pages to swipe
1341 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1342
Winson Chung321e9ee2010-08-09 13:37:56 -07001343 /*
1344 * Shortcut the most recurring case: the user is in the dragging
1345 * state and he is moving his finger. We want to intercept this
1346 * motion.
1347 */
1348 final int action = ev.getAction();
1349 if ((action == MotionEvent.ACTION_MOVE) &&
1350 (mTouchState == TOUCH_STATE_SCROLLING)) {
1351 return true;
1352 }
1353
Winson Chung321e9ee2010-08-09 13:37:56 -07001354 switch (action & MotionEvent.ACTION_MASK) {
1355 case MotionEvent.ACTION_MOVE: {
1356 /*
1357 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1358 * whether the user has moved far enough from his original down touch.
1359 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001360 if (mActivePointerId != INVALID_POINTER) {
1361 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001362 }
1363 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1364 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1365 // i.e. fall through to the next case (don't break)
1366 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1367 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001368 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001369 }
1370
1371 case MotionEvent.ACTION_DOWN: {
1372 final float x = ev.getX();
1373 final float y = ev.getY();
1374 // Remember location of down touch
1375 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001376 mDownMotionY = y;
1377 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001378 mLastMotionX = x;
1379 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001380 float[] p = mapPointFromViewToParent(this, x, y);
1381 mParentDownMotionX = p[0];
1382 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001383 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001384 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001385 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001386
Winson Chung321e9ee2010-08-09 13:37:56 -07001387 /*
1388 * If being flinged and user touches the screen, initiate drag;
1389 * otherwise don't. mScroller.isFinished should be false when
1390 * being flinged.
1391 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001392 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001393 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1394 if (finishedScrolling) {
1395 mTouchState = TOUCH_STATE_REST;
1396 mScroller.abortAnimation();
1397 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001398 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1399 mTouchState = TOUCH_STATE_SCROLLING;
1400 } else {
1401 mTouchState = TOUCH_STATE_REST;
1402 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001403 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001404
Winson Chung86f77532010-08-24 11:08:22 -07001405 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001406 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001407 if (!DISABLE_TOUCH_SIDE_PAGES) {
1408 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1409 if (getChildCount() > 0) {
1410 if (hitsPreviousPage(x, y)) {
1411 mTouchState = TOUCH_STATE_PREV_PAGE;
1412 } else if (hitsNextPage(x, y)) {
1413 mTouchState = TOUCH_STATE_NEXT_PAGE;
1414 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001415 }
1416 }
1417 }
1418 break;
1419 }
1420
Winson Chung321e9ee2010-08-09 13:37:56 -07001421 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001422 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001423 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001424 break;
1425
1426 case MotionEvent.ACTION_POINTER_UP:
1427 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001428 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001429 break;
1430 }
1431
1432 /*
1433 * The only time we want to intercept motion events is if we are in the
1434 * drag mode.
1435 */
1436 return mTouchState != TOUCH_STATE_REST;
1437 }
1438
Adam Cohenf8d28232011-02-01 21:47:00 -08001439 protected void determineScrollingStart(MotionEvent ev) {
1440 determineScrollingStart(ev, 1.0f);
1441 }
1442
Winson Chung321e9ee2010-08-09 13:37:56 -07001443 /*
1444 * Determines if we should change the touch state to start scrolling after the
1445 * user moves their touch point too far.
1446 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001447 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001448 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001449 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001450 if (pointerIndex == -1) return;
1451
1452 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001453 final float x = ev.getX(pointerIndex);
1454 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001455 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1456
Winson Chung321e9ee2010-08-09 13:37:56 -07001457 final int xDiff = (int) Math.abs(x - mLastMotionX);
1458 final int yDiff = (int) Math.abs(y - mLastMotionY);
1459
Adam Cohenf8d28232011-02-01 21:47:00 -08001460 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001461 boolean xPaged = xDiff > mPagingTouchSlop;
1462 boolean xMoved = xDiff > touchSlop;
1463 boolean yMoved = yDiff > touchSlop;
1464
Adam Cohenf8d28232011-02-01 21:47:00 -08001465 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001466 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001467 // Scroll if the user moved far enough along the X axis
1468 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001469 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001470 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001471 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001472 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001473 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1474 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001475 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001476 }
1477 }
1478
Adam Cohen7d30a372013-07-01 17:03:59 -07001479 protected float getMaxScrollProgress() {
1480 return 1.0f;
1481 }
1482
Adam Cohenf8d28232011-02-01 21:47:00 -08001483 protected void cancelCurrentPageLongPress() {
1484 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001485 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001486 // Try canceling the long press. It could also have been scheduled
1487 // by a distant descendant, so use the mAllowLongPress flag to block
1488 // everything
1489 final View currentPage = getPageAt(mCurrentPage);
1490 if (currentPage != null) {
1491 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001492 }
1493 }
1494 }
1495
Adam Cohen7d30a372013-07-01 17:03:59 -07001496 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1497 final int halfScreenSize = getViewportWidth() / 2;
1498
1499 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1500 screenCenter = Math.max(halfScreenSize, screenCenter);
1501
1502 return getScrollProgress(screenCenter, v, page);
1503 }
1504
Adam Cohenb5ba0972011-09-07 18:02:31 -07001505 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001506 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001507
Adam Cohen96d30a12013-07-16 18:13:21 -07001508 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001509 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001510
1511 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001512 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1513 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001514 return scrollProgress;
1515 }
1516
Adam Cohenedb40762013-07-18 16:45:45 -07001517 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001518 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001519 return 0;
1520 } else {
1521 return mPageScrolls[index];
1522 }
1523 }
1524
Adam Cohene0f66b52010-11-23 15:06:07 -08001525 // This curve determines how the effect of scrolling over the limits of the page dimishes
1526 // as the user pulls further and further from the bounds
1527 private float overScrollInfluenceCurve(float f) {
1528 f -= 1.0f;
1529 return f * f * f + 1.0f;
1530 }
1531
Adam Cohenb5ba0972011-09-07 18:02:31 -07001532 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001533 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001534
1535 // We want to reach the max over scroll effect when the user has
1536 // over scrolled half the size of the screen
1537 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1538
1539 if (f == 0) return;
1540
1541 // Clamp this factor, f, to -1 < f < 1
1542 if (Math.abs(f) >= 1) {
1543 f /= Math.abs(f);
1544 }
1545
1546 int overScrollAmount = (int) Math.round(f * screenSize);
1547 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001548 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001549 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001550 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001551 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001552 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001553 }
1554 invalidate();
1555 }
1556
1557 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001558 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001559
1560 float f = (amount / screenSize);
1561
1562 if (f == 0) return;
1563 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1564
Adam Cohen7bfc9792011-01-28 13:52:37 -08001565 // Clamp this factor, f, to -1 < f < 1
1566 if (Math.abs(f) >= 1) {
1567 f /= Math.abs(f);
1568 }
1569
Adam Cohene0f66b52010-11-23 15:06:07 -08001570 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001571 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001572 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001573 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001574 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001575 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001576 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001577 }
1578 invalidate();
1579 }
1580
Adam Cohenb5ba0972011-09-07 18:02:31 -07001581 protected void overScroll(float amount) {
1582 dampedOverScroll(amount);
1583 }
1584
Michael Jurkac5b262c2011-01-12 20:24:50 -08001585 protected float maxOverScroll() {
1586 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001587 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001588 float f = 1.0f;
1589 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1590 return OVERSCROLL_DAMP_FACTOR * f;
1591 }
1592
Adam Cohenf358a4b2013-07-23 16:47:31 -07001593 protected void enableFreeScroll() {
1594 setEnableFreeScroll(true, -1);
1595 }
1596
1597 protected void disableFreeScroll(int snapPage) {
1598 setEnableFreeScroll(false, snapPage);
1599 }
1600
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001601 void updateFreescrollBounds() {
1602 getOverviewModePages(mTempVisiblePagesRange);
1603 if (isLayoutRtl()) {
1604 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1605 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1606 } else {
1607 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1608 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1609 }
1610 }
1611
Adam Cohenf358a4b2013-07-23 16:47:31 -07001612 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1613 mFreeScroll = freeScroll;
1614
1615 if (snapPage == -1) {
1616 snapPage = getPageNearestToCenterOfScreen();
1617 }
1618
Adam Cohenf358a4b2013-07-23 16:47:31 -07001619 if (!mFreeScroll) {
1620 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001621 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001622 updateFreescrollBounds();
1623 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001624 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1625 setCurrentPage(mTempVisiblePagesRange[0]);
1626 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1627 setCurrentPage(mTempVisiblePagesRange[1]);
1628 }
1629 }
1630
1631 setEnableOverscroll(!freeScroll);
1632 }
1633
1634 private void setEnableOverscroll(boolean enable) {
1635 mAllowOverScroll = enable;
1636 }
1637
1638 int getNearestHoverOverPageIndex() {
1639 if (mDragView != null) {
1640 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1641 + mDragView.getTranslationX());
1642 getOverviewModePages(mTempVisiblePagesRange);
1643 int minDistance = Integer.MAX_VALUE;
1644 int minIndex = indexOfChild(mDragView);
1645 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1646 View page = getPageAt(i);
1647 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1648 int d = Math.abs(dragX - pageX);
1649 if (d < minDistance) {
1650 minIndex = i;
1651 minDistance = d;
1652 }
1653 }
1654 return minIndex;
1655 }
1656 return -1;
1657 }
1658
Winson Chung321e9ee2010-08-09 13:37:56 -07001659 @Override
1660 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001661 if (DISABLE_TOUCH_INTERACTION) {
1662 return false;
1663 }
1664
Adam Cohen1697b792013-09-17 19:08:21 -07001665 super.onTouchEvent(ev);
1666
Winson Chung45e1d6e2010-11-09 17:19:49 -08001667 // Skip touch handling if there are no pages to swipe
1668 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1669
Michael Jurkab8f06722010-10-10 15:58:46 -07001670 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001671
1672 final int action = ev.getAction();
1673
1674 switch (action & MotionEvent.ACTION_MASK) {
1675 case MotionEvent.ACTION_DOWN:
1676 /*
1677 * If being flinged and user touches, stop the fling. isFinished
1678 * will be false if being flinged.
1679 */
1680 if (!mScroller.isFinished()) {
1681 mScroller.abortAnimation();
1682 }
1683
1684 // Remember where the motion event started
1685 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001686 mDownMotionY = mLastMotionY = ev.getY();
1687 mDownScrollX = getScrollX();
1688 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1689 mParentDownMotionX = p[0];
1690 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001691 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001692 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001693 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001694
Michael Jurka0142d492010-08-25 17:46:15 -07001695 if (mTouchState == TOUCH_STATE_SCROLLING) {
1696 pageBeginMoving();
1697 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001698 break;
1699
1700 case MotionEvent.ACTION_MOVE:
1701 if (mTouchState == TOUCH_STATE_SCROLLING) {
1702 // Scroll to follow the motion event
1703 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001704
1705 if (pointerIndex == -1) return true;
1706
Winson Chung321e9ee2010-08-09 13:37:56 -07001707 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001708 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001709
Adam Cohenaefd4e12011-02-14 16:39:38 -08001710 mTotalMotionX += Math.abs(deltaX);
1711
Winson Chungc0844aa2011-02-02 15:25:58 -08001712 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1713 // keep the remainder because we are actually testing if we've moved from the last
1714 // scrolled position (which is discrete).
1715 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001716 mTouchX += deltaX;
1717 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1718 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001719 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001720 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001721 } else {
1722 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001723 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001724 mLastMotionX = x;
1725 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001726 } else {
1727 awakenScrollBars();
1728 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001729 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1730 // Update the last motion position
1731 mLastMotionX = ev.getX();
1732 mLastMotionY = ev.getY();
1733
1734 // Update the parent down so that our zoom animations take this new movement into
1735 // account
1736 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1737 mParentDownMotionX = pt[0];
1738 mParentDownMotionY = pt[1];
1739 updateDragViewTranslationDuringDrag();
1740
1741 // Find the closest page to the touch point
1742 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001743
1744 // Change the drag view if we are hovering over the drop target
1745 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1746 (int) mParentDownMotionX, (int) mParentDownMotionY);
1747 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1748
Adam Cohen7d30a372013-07-01 17:03:59 -07001749 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1750 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1751 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1752 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1753
Adam Cohenf358a4b2013-07-23 16:47:31 -07001754 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1755 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1756 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001757 mTempVisiblePagesRange[0] = 0;
1758 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001759 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001760 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1761 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1762 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1763 mSidePageHoverIndex = pageUnderPointIndex;
1764 mSidePageHoverRunnable = new Runnable() {
1765 @Override
1766 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001767 // Setup the scroll to the correct page before we swap the views
1768 snapToPage(pageUnderPointIndex);
1769
1770 // For each of the pages between the paged view and the drag view,
1771 // animate them from the previous position to the new position in
1772 // the layout (as a result of the drag view moving in the layout)
1773 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1774 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1775 dragViewIndex + 1 : pageUnderPointIndex;
1776 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1777 dragViewIndex - 1 : pageUnderPointIndex;
1778 for (int i = lowerIndex; i <= upperIndex; ++i) {
1779 View v = getChildAt(i);
1780 // dragViewIndex < pageUnderPointIndex, so after we remove the
1781 // drag view all subsequent views to pageUnderPointIndex will
1782 // shift down.
1783 int oldX = getViewportOffsetX() + getChildOffset(i);
1784 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1785
1786 // Animate the view translation from its old position to its new
1787 // position
1788 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1789 if (anim != null) {
1790 anim.cancel();
1791 }
1792
1793 v.setTranslationX(oldX - newX);
1794 anim = new AnimatorSet();
1795 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1796 anim.playTogether(
1797 ObjectAnimator.ofFloat(v, "translationX", 0f));
1798 anim.start();
1799 v.setTag(anim);
1800 }
1801
1802 removeView(mDragView);
1803 onRemoveView(mDragView, false);
1804 addView(mDragView, pageUnderPointIndex);
1805 onAddView(mDragView, pageUnderPointIndex);
1806 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001807 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001808 }
1809 };
1810 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1811 }
1812 } else {
1813 removeCallbacks(mSidePageHoverRunnable);
1814 mSidePageHoverIndex = -1;
1815 }
Adam Cohen564976a2010-10-13 18:52:07 -07001816 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001817 determineScrollingStart(ev);
1818 }
1819 break;
1820
1821 case MotionEvent.ACTION_UP:
1822 if (mTouchState == TOUCH_STATE_SCROLLING) {
1823 final int activePointerId = mActivePointerId;
1824 final int pointerIndex = ev.findPointerIndex(activePointerId);
1825 final float x = ev.getX(pointerIndex);
1826 final VelocityTracker velocityTracker = mVelocityTracker;
1827 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1828 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001829 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001830 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001831 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1832 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001833
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001834 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1835
Adam Cohen00481b32011-11-18 12:03:48 -08001836 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001837 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001838
Adam Cohenf358a4b2013-07-23 16:47:31 -07001839 if (!mFreeScroll) {
1840 // In the case that the page is moved far to one direction and then is flung
1841 // in the opposite direction, we use a threshold to determine whether we should
1842 // just return to the starting page, or if we should skip one further.
1843 boolean returnToOriginalPage = false;
1844 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1845 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1846 returnToOriginalPage = true;
1847 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001848
Adam Cohenf358a4b2013-07-23 16:47:31 -07001849 int finalPage;
1850 // We give flings precedence over large moves, which is why we short-circuit our
1851 // test for a large move if a fling has been registered. That is, a large
1852 // move to the left and fling to the right will register as a fling to the right.
1853 final boolean isRtl = isLayoutRtl();
1854 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1855 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1856 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1857 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1858 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1859 snapToPageWithVelocity(finalPage, velocityX);
1860 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1861 (isFling && isVelocityXLeft)) &&
1862 mCurrentPage < getChildCount() - 1) {
1863 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1864 snapToPageWithVelocity(finalPage, velocityX);
1865 } else {
1866 snapToDestination();
1867 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1868 // at this point we have not moved beyond the touch slop
1869 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1870 // we can just page
1871 int nextPage = Math.max(0, mCurrentPage - 1);
1872 if (nextPage != mCurrentPage) {
1873 snapToPage(nextPage);
1874 } else {
1875 snapToDestination();
1876 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001877 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001878 if (!mScroller.isFinished()) {
1879 mScroller.abortAnimation();
1880 }
1881
1882 float scaleX = getScaleX();
1883 int vX = (int) (-velocityX * scaleX);
1884 int initialScrollX = (int) (getScrollX() * scaleX);
1885
1886 mScroller.fling(initialScrollX,
1887 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1888 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001889 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001890 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001891 // at this point we have not moved beyond the touch slop
1892 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1893 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001894 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1895 if (nextPage != mCurrentPage) {
1896 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001897 } else {
1898 snapToDestination();
1899 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001900 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1901 // Update the last motion position
1902 mLastMotionX = ev.getX();
1903 mLastMotionY = ev.getY();
1904
1905 // Update the parent down so that our zoom animations take this new movement into
1906 // account
1907 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1908 mParentDownMotionX = pt[0];
1909 mParentDownMotionY = pt[1];
1910 updateDragViewTranslationDuringDrag();
1911 boolean handledFling = false;
1912 if (!DISABLE_FLING_TO_DELETE) {
1913 // Check the velocity and see if we are flinging-to-delete
1914 PointF flingToDeleteVector = isFlingingToDelete();
1915 if (flingToDeleteVector != null) {
1916 onFlingToDelete(flingToDeleteVector);
1917 handledFling = true;
1918 }
1919 }
1920 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1921 (int) mParentDownMotionY)) {
1922 onDropToDelete();
1923 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001924 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001925 if (!mCancelTap) {
1926 onUnhandledTap(ev);
1927 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001928 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001929
1930 // Remove the callback to wait for the side page hover timeout
1931 removeCallbacks(mSidePageHoverRunnable);
1932 // End any intermediate reordering states
1933 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001934 break;
1935
1936 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001937 if (mTouchState == TOUCH_STATE_SCROLLING) {
1938 snapToDestination();
1939 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001940 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001941 break;
1942
1943 case MotionEvent.ACTION_POINTER_UP:
1944 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001945 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001946 break;
1947 }
1948
1949 return true;
1950 }
1951
Adam Cohen7d30a372013-07-01 17:03:59 -07001952 public void onFlingToDelete(View v) {}
1953 public void onRemoveView(View v, boolean deletePermanently) {}
1954 public void onRemoveViewAnimationCompleted() {}
1955 public void onAddView(View v, int index) {}
1956
1957 private void resetTouchState() {
1958 releaseVelocityTracker();
1959 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001960 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001961 mTouchState = TOUCH_STATE_REST;
1962 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001963 }
1964
Adam Cohen1697b792013-09-17 19:08:21 -07001965 protected void onUnhandledTap(MotionEvent ev) {
1966 ((Launcher) getContext()).onClick(this);
1967 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001968
Winson Chung185d7162011-02-28 13:47:29 -08001969 @Override
1970 public boolean onGenericMotionEvent(MotionEvent event) {
1971 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1972 switch (event.getAction()) {
1973 case MotionEvent.ACTION_SCROLL: {
1974 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1975 final float vscroll;
1976 final float hscroll;
1977 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1978 vscroll = 0;
1979 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1980 } else {
1981 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1982 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1983 }
1984 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001985 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1986 : (hscroll > 0 || vscroll > 0);
1987 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001988 scrollRight();
1989 } else {
1990 scrollLeft();
1991 }
1992 return true;
1993 }
1994 }
1995 }
1996 }
1997 return super.onGenericMotionEvent(event);
1998 }
1999
Michael Jurkab8f06722010-10-10 15:58:46 -07002000 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
2001 if (mVelocityTracker == null) {
2002 mVelocityTracker = VelocityTracker.obtain();
2003 }
2004 mVelocityTracker.addMovement(ev);
2005 }
2006
2007 private void releaseVelocityTracker() {
2008 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002009 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07002010 mVelocityTracker.recycle();
2011 mVelocityTracker = null;
2012 }
2013 }
2014
Winson Chung321e9ee2010-08-09 13:37:56 -07002015 private void onSecondaryPointerUp(MotionEvent ev) {
2016 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
2017 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
2018 final int pointerId = ev.getPointerId(pointerIndex);
2019 if (pointerId == mActivePointerId) {
2020 // This was our active pointer going up. Choose a new
2021 // active pointer and adjust accordingly.
2022 // TODO: Make this decision more intelligent.
2023 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2024 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
2025 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08002026 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07002027 mActivePointerId = ev.getPointerId(newPointerIndex);
2028 if (mVelocityTracker != null) {
2029 mVelocityTracker.clear();
2030 }
2031 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08002032 }
2033
Winson Chung321e9ee2010-08-09 13:37:56 -07002034 @Override
2035 public void requestChildFocus(View child, View focused) {
2036 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002037 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002038 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002039 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002040 }
2041 }
2042
Winson Chung1908d072011-02-24 18:09:44 -08002043 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002044 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002045 }
2046
Adam Cohen7d30a372013-07-01 17:03:59 -07002047 int getPageNearestToPoint(float x) {
2048 int index = 0;
2049 for (int i = 0; i < getChildCount(); ++i) {
2050 if (x < getChildAt(i).getRight() - getScrollX()) {
2051 return index;
2052 } else {
2053 index++;
2054 }
2055 }
2056 return Math.min(index, getChildCount() - 1);
2057 }
2058
Adam Cohend19d3ca2010-09-15 14:43:42 -07002059 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002060 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002061 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002062 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002063 final int childCount = getChildCount();
2064 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002065 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002066 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002067 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002068 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002069 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2070 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2071 minDistanceFromScreenCenter = distanceFromScreenCenter;
2072 minDistanceFromScreenCenterIndex = i;
2073 }
2074 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002075 return minDistanceFromScreenCenterIndex;
2076 }
2077
2078 protected void snapToDestination() {
2079 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002080 }
2081
Adam Cohene0f66b52010-11-23 15:06:07 -08002082 private static class ScrollInterpolator implements Interpolator {
2083 public ScrollInterpolator() {
2084 }
2085
2086 public float getInterpolation(float t) {
2087 t -= 1.0f;
2088 return t*t*t*t*t + 1;
2089 }
2090 }
2091
2092 // We want the duration of the page snap animation to be influenced by the distance that
2093 // the screen has to travel, however, we don't want this duration to be effected in a
2094 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2095 // of travel has on the overall snap duration.
2096 float distanceInfluenceForSnapDuration(float f) {
2097 f -= 0.5f; // center the values about 0.
2098 f *= 0.3f * Math.PI / 2.0f;
2099 return (float) Math.sin(f);
2100 }
2101
Michael Jurka0142d492010-08-25 17:46:15 -07002102 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002103 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002104 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002105
Adam Cohenedb40762013-07-18 16:45:45 -07002106 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002107 int delta = newX - mUnboundedScrollX;
2108 int duration = 0;
2109
Adam Cohen265b9a62011-12-07 14:37:18 -08002110 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002111 // If the velocity is low enough, then treat this more as an automatic page advance
2112 // as opposed to an apparent physical response to flinging
2113 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2114 return;
2115 }
2116
2117 // Here we compute a "distance" that will be used in the computation of the overall
2118 // snap duration. This is a function of the actual distance that needs to be traveled;
2119 // we keep this value close to half screen size in order to reduce the variance in snap
2120 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002121 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002122 float distance = halfScreenSize + halfScreenSize *
2123 distanceInfluenceForSnapDuration(distanceRatio);
2124
2125 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002126 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002127
2128 // we want the page's snap velocity to approximately match the velocity at which the
2129 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002130 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2131 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002132
2133 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002134 }
2135
2136 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002137 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002138 }
2139
Adam Cohen7d30a372013-07-01 17:03:59 -07002140 protected void snapToPageImmediately(int whichPage) {
2141 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2142 }
2143
Michael Jurka0142d492010-08-25 17:46:15 -07002144 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002145 snapToPage(whichPage, duration, false);
2146 }
2147
2148 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002149 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002150
Adam Cohenedb40762013-07-18 16:45:45 -07002151 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002152 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002153 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002154 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002155 }
2156
2157 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002158 snapToPage(whichPage, delta, duration, false);
2159 }
Michael Jurka0142d492010-08-25 17:46:15 -07002160
Adam Cohen7d30a372013-07-01 17:03:59 -07002161 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2162 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002163 View focusedChild = getFocusedChild();
2164 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002165 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002166 focusedChild.clearFocus();
2167 }
2168
Adam Cohen53805212013-10-01 10:39:23 -07002169 sendScrollAccessibilityEvent();
2170
Michael Jurka0142d492010-08-25 17:46:15 -07002171 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002172 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002173 if (immediate) {
2174 duration = 0;
2175 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002176 duration = Math.abs(delta);
2177 }
2178
Adam Cohenf358a4b2013-07-23 16:47:31 -07002179 if (!mScroller.isFinished()) {
2180 mScroller.abortAnimation();
2181 }
Adam Cohen68d73932010-11-15 10:50:58 -08002182 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002183
Michael Jurka0142d492010-08-25 17:46:15 -07002184 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002185
2186 // Trigger a compute() to finish switching pages if necessary
2187 if (immediate) {
2188 computeScroll();
2189 }
2190
Winson Chung9c0565f2013-07-19 13:49:06 -07002191 // Defer loading associated pages until the scroll settles
2192 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2193
Adam Cohen7d30a372013-07-01 17:03:59 -07002194 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002195 invalidate();
2196 }
2197
Winson Chung321e9ee2010-08-09 13:37:56 -07002198 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002199 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002200 }
2201
2202 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002203 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002204 }
2205
Winson Chung86f77532010-08-24 11:08:22 -07002206 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002207 int result = -1;
2208 if (v != null) {
2209 ViewParent vp = v.getParent();
2210 int count = getChildCount();
2211 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002212 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002213 return i;
2214 }
2215 }
2216 }
2217 return result;
2218 }
2219
2220 /**
2221 * @return True is long presses are still allowed for the current touch
2222 */
2223 public boolean allowLongPress() {
2224 return mAllowLongPress;
2225 }
2226
Adam Cohendbdff6b2013-09-18 19:09:15 -07002227 @Override
2228 public boolean performLongClick() {
2229 mCancelTap = true;
2230 return super.performLongClick();
2231 }
2232
Michael Jurka0142d492010-08-25 17:46:15 -07002233 /**
2234 * Set true to allow long-press events to be triggered, usually checked by
2235 * {@link Launcher} to accept or block dpad-initiated long-presses.
2236 */
2237 public void setAllowLongPress(boolean allowLongPress) {
2238 mAllowLongPress = allowLongPress;
2239 }
2240
Winson Chung321e9ee2010-08-09 13:37:56 -07002241 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002242 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002243
2244 SavedState(Parcelable superState) {
2245 super(superState);
2246 }
2247
2248 private SavedState(Parcel in) {
2249 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002250 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002251 }
2252
2253 @Override
2254 public void writeToParcel(Parcel out, int flags) {
2255 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002256 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002257 }
2258
2259 public static final Parcelable.Creator<SavedState> CREATOR =
2260 new Parcelable.Creator<SavedState>() {
2261 public SavedState createFromParcel(Parcel in) {
2262 return new SavedState(in);
2263 }
2264
2265 public SavedState[] newArray(int size) {
2266 return new SavedState[size];
2267 }
2268 };
2269 }
2270
Winson Chungf314b0e2011-08-16 11:54:27 -07002271 protected void loadAssociatedPages(int page) {
2272 loadAssociatedPages(page, false);
2273 }
2274 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002275 if (mContentIsRefreshable) {
2276 final int count = getChildCount();
2277 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002278 int lowerPageBound = getAssociatedLowerPageBound(page);
2279 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002280 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2281 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002282 // First, clear any pages that should no longer be loaded
2283 for (int i = 0; i < count; ++i) {
2284 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002285 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002286 if (layout.getPageChildCount() > 0) {
2287 layout.removeAllViewsOnPage();
2288 }
2289 mDirtyPageContent.set(i, true);
2290 }
2291 }
2292 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002293 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002294 if ((i != page) && immediateAndOnly) {
2295 continue;
2296 }
Michael Jurka0142d492010-08-25 17:46:15 -07002297 if (lowerPageBound <= i && i <= upperPageBound) {
2298 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002299 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002300 mDirtyPageContent.set(i, false);
2301 }
Winson Chung86f77532010-08-24 11:08:22 -07002302 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002303 }
2304 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002305 }
2306 }
2307
Winson Chunge3193b92010-09-10 11:44:42 -07002308 protected int getAssociatedLowerPageBound(int page) {
2309 return Math.max(0, page - 1);
2310 }
2311 protected int getAssociatedUpperPageBound(int page) {
2312 final int count = getChildCount();
2313 return Math.min(page + 1, count - 1);
2314 }
2315
Winson Chung86f77532010-08-24 11:08:22 -07002316 /**
2317 * This method is called ONLY to synchronize the number of pages that the paged view has.
2318 * To actually fill the pages with information, implement syncPageItems() below. It is
2319 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2320 * and therefore, individual page items do not need to be updated in this method.
2321 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002322 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002323
2324 /**
2325 * This method is called to synchronize the items that are on a particular page. If views on
2326 * the page can be reused, then they should be updated within this method.
2327 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002328 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002329
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002330 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002331 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002332 }
2333 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002334 invalidatePageData(currentPage, false);
2335 }
2336 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002337 if (!mIsDataReady) {
2338 return;
2339 }
2340
Michael Jurka0142d492010-08-25 17:46:15 -07002341 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002342 // Force all scrolling-related behavior to end
2343 mScroller.forceFinished(true);
2344 mNextPage = INVALID_PAGE;
2345
Michael Jurka0142d492010-08-25 17:46:15 -07002346 // Update all the pages
2347 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002348
Winson Chung5a808352011-06-27 19:08:49 -07002349 // We must force a measure after we've loaded the pages to update the content width and
2350 // to determine the full scroll width
2351 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2352 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2353
2354 // Set a new page as the current page if necessary
2355 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002356 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002357 }
2358
Michael Jurka0142d492010-08-25 17:46:15 -07002359 // Mark each of the pages as dirty
2360 final int count = getChildCount();
2361 mDirtyPageContent.clear();
2362 for (int i = 0; i < count; ++i) {
2363 mDirtyPageContent.add(true);
2364 }
2365
2366 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002367 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002368 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002369 }
Adam Cohen06559042013-09-29 18:30:56 -07002370 if (isPageMoving()) {
2371 // If the page is moving, then snap it to the final position to ensure we don't get
2372 // stuck between pages
2373 snapToDestination();
2374 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002375 }
Winson Chung007c6982011-06-14 13:27:53 -07002376
Adam Cohen7d30a372013-07-01 17:03:59 -07002377 // Animate the drag view back to the original position
2378 void animateDragViewToOriginalPosition() {
2379 if (mDragView != null) {
2380 AnimatorSet anim = new AnimatorSet();
2381 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2382 anim.playTogether(
2383 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002384 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2385 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2386 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002387 anim.addListener(new AnimatorListenerAdapter() {
2388 @Override
2389 public void onAnimationEnd(Animator animation) {
2390 onPostReorderingAnimationCompleted();
2391 }
2392 });
2393 anim.start();
2394 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002395 }
2396
Adam Cohen7d30a372013-07-01 17:03:59 -07002397 protected void onStartReordering() {
2398 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2399 mTouchState = TOUCH_STATE_REORDERING;
2400 mIsReordering = true;
2401
Adam Cohen7d30a372013-07-01 17:03:59 -07002402 // We must invalidate to trigger a redraw to update the layers such that the drag view
2403 // is always drawn on top
2404 invalidate();
2405 }
2406
2407 private void onPostReorderingAnimationCompleted() {
2408 // Trigger the callback when reordering has settled
2409 --mPostReorderingPreZoomInRemainingAnimationCount;
2410 if (mPostReorderingPreZoomInRunnable != null &&
2411 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2412 mPostReorderingPreZoomInRunnable.run();
2413 mPostReorderingPreZoomInRunnable = null;
2414 }
2415 }
2416
2417 protected void onEndReordering() {
2418 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002419 }
2420
Adam Cohenf358a4b2013-07-23 16:47:31 -07002421 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002422 int dragViewIndex = indexOfChild(v);
2423
2424 if (mTouchState != TOUCH_STATE_REST) return false;
2425
Adam Cohen7d30a372013-07-01 17:03:59 -07002426 mTempVisiblePagesRange[0] = 0;
2427 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002428 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002429 mReorderingStarted = true;
2430
2431 // Check if we are within the reordering range
2432 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002433 dragViewIndex <= mTempVisiblePagesRange[1]) {
2434 // Find the drag view under the pointer
2435 mDragView = getChildAt(dragViewIndex);
2436 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2437 mDragViewBaselineLeft = mDragView.getLeft();
2438 disableFreeScroll(-1);
2439 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002440 return true;
2441 }
2442 return false;
2443 }
2444
2445 boolean isReordering(boolean testTouchState) {
2446 boolean state = mIsReordering;
2447 if (testTouchState) {
2448 state &= (mTouchState == TOUCH_STATE_REORDERING);
2449 }
2450 return state;
2451 }
2452 void endReordering() {
2453 // For simplicity, we call endReordering sometimes even if reordering was never started.
2454 // In that case, we don't want to do anything.
2455 if (!mReorderingStarted) return;
2456 mReorderingStarted = false;
2457
2458 // If we haven't flung-to-delete the current child, then we just animate the drag view
2459 // back into position
2460 final Runnable onCompleteRunnable = new Runnable() {
2461 @Override
2462 public void run() {
2463 onEndReordering();
2464 }
2465 };
2466 if (!mDeferringForDelete) {
2467 mPostReorderingPreZoomInRunnable = new Runnable() {
2468 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002469 onCompleteRunnable.run();
2470 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002471 };
2472 };
2473
2474 mPostReorderingPreZoomInRemainingAnimationCount =
2475 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2476 // Snap to the current page
2477 snapToPage(indexOfChild(mDragView), 0);
2478 // Animate the drag view back to the front position
2479 animateDragViewToOriginalPosition();
2480 } else {
2481 // Handled in post-delete-animation-callbacks
2482 }
2483 }
2484
Adam Cohen7d30a372013-07-01 17:03:59 -07002485 /*
2486 * Flinging to delete - IN PROGRESS
2487 */
2488 private PointF isFlingingToDelete() {
2489 ViewConfiguration config = ViewConfiguration.get(getContext());
2490 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2491
2492 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2493 // Do a quick dot product test to ensure that we are flinging upwards
2494 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2495 mVelocityTracker.getYVelocity());
2496 PointF upVec = new PointF(0f, -1f);
2497 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2498 (vel.length() * upVec.length()));
2499 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2500 return vel;
2501 }
2502 }
2503 return null;
2504 }
2505
2506 /**
2507 * Creates an animation from the current drag view along its current velocity vector.
2508 * For this animation, the alpha runs for a fixed duration and we update the position
2509 * progressively.
2510 */
2511 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2512 private View mDragView;
2513 private PointF mVelocity;
2514 private Rect mFrom;
2515 private long mPrevTime;
2516 private float mFriction;
2517
2518 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2519
2520 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2521 long startTime, float friction) {
2522 mDragView = dragView;
2523 mVelocity = vel;
2524 mFrom = from;
2525 mPrevTime = startTime;
2526 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2527 }
2528
2529 @Override
2530 public void onAnimationUpdate(ValueAnimator animation) {
2531 float t = ((Float) animation.getAnimatedValue()).floatValue();
2532 long curTime = AnimationUtils.currentAnimationTimeMillis();
2533
2534 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2535 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2536
2537 mDragView.setTranslationX(mFrom.left);
2538 mDragView.setTranslationY(mFrom.top);
2539 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2540
2541 mVelocity.x *= mFriction;
2542 mVelocity.y *= mFriction;
2543 mPrevTime = curTime;
2544 }
2545 };
2546
2547 private static final int ANIM_TAG_KEY = 100;
2548
2549 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2550 return new Runnable() {
2551 @Override
2552 public void run() {
2553 int dragViewIndex = indexOfChild(dragView);
2554
2555 // For each of the pages around the drag view, animate them from the previous
2556 // position to the new position in the layout (as a result of the drag view moving
2557 // in the layout)
2558 // NOTE: We can make an assumption here because we have side-bound pages that we
2559 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002560 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002561 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2562 boolean slideFromLeft = (isLastWidgetPage ||
2563 dragViewIndex > mTempVisiblePagesRange[0]);
2564
2565 // Setup the scroll to the correct page before we swap the views
2566 if (slideFromLeft) {
2567 snapToPageImmediately(dragViewIndex - 1);
2568 }
2569
2570 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2571 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2572 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2573 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2574 ArrayList<Animator> animations = new ArrayList<Animator>();
2575 for (int i = lowerIndex; i <= upperIndex; ++i) {
2576 View v = getChildAt(i);
2577 // dragViewIndex < pageUnderPointIndex, so after we remove the
2578 // drag view all subsequent views to pageUnderPointIndex will
2579 // shift down.
2580 int oldX = 0;
2581 int newX = 0;
2582 if (slideFromLeft) {
2583 if (i == 0) {
2584 // Simulate the page being offscreen with the page spacing
2585 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2586 - mPageSpacing;
2587 } else {
2588 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2589 }
2590 newX = getViewportOffsetX() + getChildOffset(i);
2591 } else {
2592 oldX = getChildOffset(i) - getChildOffset(i - 1);
2593 newX = 0;
2594 }
2595
2596 // Animate the view translation from its old position to its new
2597 // position
2598 AnimatorSet anim = (AnimatorSet) v.getTag();
2599 if (anim != null) {
2600 anim.cancel();
2601 }
2602
2603 // Note: Hacky, but we want to skip any optimizations to not draw completely
2604 // hidden views
2605 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2606 v.setTranslationX(oldX - newX);
2607 anim = new AnimatorSet();
2608 anim.playTogether(
2609 ObjectAnimator.ofFloat(v, "translationX", 0f),
2610 ObjectAnimator.ofFloat(v, "alpha", 1f));
2611 animations.add(anim);
2612 v.setTag(ANIM_TAG_KEY, anim);
2613 }
2614
2615 AnimatorSet slideAnimations = new AnimatorSet();
2616 slideAnimations.playTogether(animations);
2617 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2618 slideAnimations.addListener(new AnimatorListenerAdapter() {
2619 @Override
2620 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002621 mDeferringForDelete = false;
2622 onEndReordering();
2623 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002624 }
2625 });
2626 slideAnimations.start();
2627
2628 removeView(dragView);
2629 onRemoveView(dragView, true);
2630 }
2631 };
2632 }
2633
2634 public void onFlingToDelete(PointF vel) {
2635 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2636
2637 // NOTE: Because it takes time for the first frame of animation to actually be
2638 // called and we expect the animation to be a continuation of the fling, we have
2639 // to account for the time that has elapsed since the fling finished. And since
2640 // we don't have a startDelay, we will always get call to update when we call
2641 // start() (which we want to ignore).
2642 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2643 private int mCount = -1;
2644 private long mStartTime;
2645 private float mOffset;
2646 /* Anonymous inner class ctor */ {
2647 mStartTime = startTime;
2648 }
2649
2650 @Override
2651 public float getInterpolation(float t) {
2652 if (mCount < 0) {
2653 mCount++;
2654 } else if (mCount == 0) {
2655 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2656 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2657 mCount++;
2658 }
2659 return Math.min(1f, mOffset + t);
2660 }
2661 };
2662
2663 final Rect from = new Rect();
2664 final View dragView = mDragView;
2665 from.left = (int) dragView.getTranslationX();
2666 from.top = (int) dragView.getTranslationY();
2667 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2668 from, startTime, FLING_TO_DELETE_FRICTION);
2669
2670 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2671
2672 // Create and start the animation
2673 ValueAnimator mDropAnim = new ValueAnimator();
2674 mDropAnim.setInterpolator(tInterpolator);
2675 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2676 mDropAnim.setFloatValues(0f, 1f);
2677 mDropAnim.addUpdateListener(updateCb);
2678 mDropAnim.addListener(new AnimatorListenerAdapter() {
2679 public void onAnimationEnd(Animator animation) {
2680 onAnimationEndRunnable.run();
2681 }
2682 });
2683 mDropAnim.start();
2684 mDeferringForDelete = true;
2685 }
2686
2687 /* Drag to delete */
2688 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2689 if (mDeleteDropTarget != null) {
2690 mAltTmpRect.set(0, 0, 0, 0);
2691 View parent = (View) mDeleteDropTarget.getParent();
2692 if (parent != null) {
2693 parent.getGlobalVisibleRect(mAltTmpRect);
2694 }
2695 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2696 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2697 return mTmpRect.contains(x, y);
2698 }
2699 return false;
2700 }
2701
2702 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2703
2704 private void onDropToDelete() {
2705 final View dragView = mDragView;
2706
2707 final float toScale = 0f;
2708 final float toAlpha = 0f;
2709
2710 // Create and start the complex animation
2711 ArrayList<Animator> animations = new ArrayList<Animator>();
2712 AnimatorSet motionAnim = new AnimatorSet();
2713 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2714 motionAnim.playTogether(
2715 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2716 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2717 animations.add(motionAnim);
2718
2719 AnimatorSet alphaAnim = new AnimatorSet();
2720 alphaAnim.setInterpolator(new LinearInterpolator());
2721 alphaAnim.playTogether(
2722 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2723 animations.add(alphaAnim);
2724
2725 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2726
2727 AnimatorSet anim = new AnimatorSet();
2728 anim.playTogether(animations);
2729 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2730 anim.addListener(new AnimatorListenerAdapter() {
2731 public void onAnimationEnd(Animator animation) {
2732 onAnimationEndRunnable.run();
2733 }
2734 });
2735 anim.start();
2736
2737 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002738 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002739
2740 /* Accessibility */
2741 @Override
2742 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2743 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002744 info.setScrollable(getPageCount() > 1);
2745 if (getCurrentPage() < getPageCount() - 1) {
2746 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2747 }
2748 if (getCurrentPage() > 0) {
2749 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2750 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002751 }
2752
2753 @Override
Alan Viverette254139a2013-10-08 13:13:46 -07002754 public void sendAccessibilityEvent(int eventType) {
2755 // Don't let the view send real scroll events.
2756 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2757 super.sendAccessibilityEvent(eventType);
2758 }
2759 }
2760
2761 @Override
Winson Chung6a0f57d2011-06-29 20:10:49 -07002762 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2763 super.onInitializeAccessibilityEvent(event);
2764 event.setScrollable(true);
Winson Chung6a0f57d2011-06-29 20:10:49 -07002765 }
2766
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002767 @Override
2768 public boolean performAccessibilityAction(int action, Bundle arguments) {
2769 if (super.performAccessibilityAction(action, arguments)) {
2770 return true;
2771 }
2772 switch (action) {
2773 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2774 if (getCurrentPage() < getPageCount() - 1) {
2775 scrollRight();
2776 return true;
2777 }
2778 } break;
2779 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2780 if (getCurrentPage() > 0) {
2781 scrollLeft();
2782 return true;
2783 }
2784 } break;
2785 }
2786 return false;
2787 }
2788
Adam Cohen0ffac432013-07-10 11:19:26 -07002789 protected String getCurrentPageDescription() {
2790 return String.format(getContext().getString(R.string.default_scroll_format),
2791 getNextPage() + 1, getChildCount());
2792 }
2793
Winson Chungd11265e2011-08-30 13:37:23 -07002794 @Override
2795 public boolean onHoverEvent(android.view.MotionEvent event) {
2796 return true;
2797 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002798}