blob: d8fc98330b32c325fb6fa5424d845f1018d45f36 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
35import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070036import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070037import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080038import android.view.InputDevice;
39import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070040import android.view.MotionEvent;
41import android.view.VelocityTracker;
42import android.view.View;
43import android.view.ViewConfiguration;
44import android.view.ViewGroup;
45import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070046import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070047import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070049import android.view.animation.AnimationUtils;
50import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080051import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070052import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070053import android.widget.Scroller;
54
Winson Chung6a0f57d2011-06-29 20:10:49 -070055import java.util.ArrayList;
56
Winson Chungc58497e2013-09-03 17:48:37 -070057interface Page {
58 public int getPageChildCount();
59 public View getChildOnPageAt(int i);
60 public void removeAllViewsOnPage();
61 public void removeViewOnPageAt(int i);
62 public int indexOfChildOnPage(View v);
63}
64
Winson Chung321e9ee2010-08-09 13:37:56 -070065/**
66 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070067 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070068 */
Michael Jurka8b805b12012-04-18 14:23:14 -070069public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070070 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070071 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070072 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070073
Winson Chung86f77532010-08-24 11:08:22 -070074 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070075 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070076
Adam Cohen7d30a372013-07-01 17:03:59 -070077 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070078 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070079 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070080
Adam Cohenb5ba0972011-09-07 18:02:31 -070081 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070082 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080083
Adam Cohenb64cb5a2011-02-15 13:53:42 -080084 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080085 // The page is moved more than halfway, automatically move to the next page on touch up.
86 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080087
Adam Cohen265b9a62011-12-07 14:37:18 -080088 // The following constants need to be scaled based on density. The scaled versions will be
89 // assigned to the corresponding member variables below.
90 private static final int FLING_THRESHOLD_VELOCITY = 500;
91 private static final int MIN_SNAP_VELOCITY = 1500;
92 private static final int MIN_FLING_VELOCITY = 250;
93
Adam Cohen7d30a372013-07-01 17:03:59 -070094 // We are disabling touch interaction of the widget region for factory ROM.
95 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070096 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070097 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070098
Adam Cohenf358a4b2013-07-23 16:47:31 -070099 private boolean mFreeScroll = false;
100 private int mFreeScrollMinScrollX = -1;
101 private int mFreeScrollMaxScrollX = -1;
102
Winson Chung8aad6102012-05-11 16:27:49 -0700103 static final int AUTOMATIC_PAGE_SPACING = -1;
104
Adam Cohen265b9a62011-12-07 14:37:18 -0800105 protected int mFlingThresholdVelocity;
106 protected int mMinFlingVelocity;
107 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700108
Adam Cohenb5ba0972011-09-07 18:02:31 -0700109 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700110 protected float mSmoothingTime;
111 protected float mTouchX;
112
113 protected boolean mFirstLayout = true;
114
115 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700116 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700117 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700118
Michael Jurka0142d492010-08-25 17:46:15 -0700119 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800120 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700121 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700122 private VelocityTracker mVelocityTracker;
123
Adam Cohen7d30a372013-07-01 17:03:59 -0700124 private float mParentDownMotionX;
125 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700127 private float mDownMotionY;
128 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700129 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800130 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800131 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800132 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800133 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700134 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700135
Adam Cohendbdff6b2013-09-18 19:09:15 -0700136 private boolean mCancelTap;
137
Adam Cohenedb40762013-07-18 16:45:45 -0700138 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700139
Michael Jurka0142d492010-08-25 17:46:15 -0700140 protected final static int TOUCH_STATE_REST = 0;
141 protected final static int TOUCH_STATE_SCROLLING = 1;
142 protected final static int TOUCH_STATE_PREV_PAGE = 2;
143 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700144 protected final static int TOUCH_STATE_REORDERING = 4;
145
Adam Cohene45440e2010-10-14 18:33:38 -0700146 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700147
Michael Jurka0142d492010-08-25 17:46:15 -0700148 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700149 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700150
Michael Jurka0142d492010-08-25 17:46:15 -0700151 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700152
Michael Jurka7426c422010-11-11 15:23:47 -0800153 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700154 private int mPagingTouchSlop;
155 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700156 protected int mPageSpacing;
157 protected int mPageLayoutPaddingTop;
158 protected int mPageLayoutPaddingBottom;
159 protected int mPageLayoutPaddingLeft;
160 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700161 protected int mPageLayoutWidthGap;
162 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700163 protected int mCellCountX = 0;
164 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700165 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800166 protected boolean mAllowOverScroll = true;
167 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800168 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700169 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700170
Michael Jurka8b805b12012-04-18 14:23:14 -0700171 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800172 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
173 // the screens from continuing to translate beyond the normal bounds.
174 protected int mOverScrollX;
175
Michael Jurka5f1c5092010-09-03 14:15:02 -0700176 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700177
Michael Jurka5f1c5092010-09-03 14:15:02 -0700178 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700179
Winson Chung86f77532010-08-24 11:08:22 -0700180 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700181
Michael Jurkae326f182011-11-21 14:05:46 -0800182 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700183
Michael Jurka0142d492010-08-25 17:46:15 -0700184 // If true, syncPages and syncPageItems will be called to refresh pages
185 protected boolean mContentIsRefreshable = true;
186
187 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700188 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700189
190 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
191 // to switch to a new page
192 protected boolean mUsePagingTouchSlop = true;
193
Michael Jurka8b805b12012-04-18 14:23:14 -0700194 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700195 // (SmoothPagedView does this)
196 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700197 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700198
Patrick Dubroy1262e362010-10-06 15:49:50 -0700199 protected boolean mIsPageMoving = false;
200
Winson Chungf0ea4d32011-06-06 14:27:16 -0700201 // All syncs and layout passes are deferred until data is ready.
202 protected boolean mIsDataReady = false;
203
Adam Cohen7d30a372013-07-01 17:03:59 -0700204 protected boolean mAllowLongPress = true;
205
Winson Chungd2be3812013-07-16 11:11:32 -0700206 // Page Indicator
207 private int mPageIndicatorViewId;
208 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700209 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700210
Adam Cohen7d30a372013-07-01 17:03:59 -0700211 // The viewport whether the pages are to be contained (the actual view may be larger than the
212 // viewport)
213 private Rect mViewport = new Rect();
214
215 // Reordering
216 // We use the min scale to determine how much to expand the actually PagedView measured
217 // dimensions such that when we are zoomed out, the view is not clipped
218 private int REORDERING_DROP_REPOSITION_DURATION = 200;
219 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
220 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700221 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700222 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700223 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700224 protected View mDragView;
225 protected AnimatorSet mZoomInOutAnim;
226 private Runnable mSidePageHoverRunnable;
227 private int mSidePageHoverIndex = -1;
228 // This variable's scope is only for the duration of startReordering() and endReordering()
229 private boolean mReorderingStarted = false;
230 // This variable's scope is for the duration of startReordering() and after the zoomIn()
231 // animation after endReordering()
232 private boolean mIsReordering;
233 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
234 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
235 private int mPostReorderingPreZoomInRemainingAnimationCount;
236 private Runnable mPostReorderingPreZoomInRunnable;
237
Adam Cohen7d30a372013-07-01 17:03:59 -0700238 // Convenience/caching
239 private Matrix mTmpInvMatrix = new Matrix();
240 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700241 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700242 private Rect mTmpRect = new Rect();
243 private Rect mAltTmpRect = new Rect();
244
245 // Fling to delete
246 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
247 private float FLING_TO_DELETE_FRICTION = 0.035f;
248 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
249 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
250 protected int mFlingToDeleteThresholdVelocity = -1400;
251 // Drag to delete
252 private boolean mDeferringForDelete = false;
253 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
254 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
255
256 // Drop to delete
257 private View mDeleteDropTarget;
258
259 private boolean mAutoComputePageSpacing = false;
260 private boolean mRecomputePageSpacing = false;
261
262 // Bouncer
263 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700264
John Spurlock77e1f472013-09-11 10:09:51 -0400265 protected final Rect mInsets = new Rect();
266
Winson Chung86f77532010-08-24 11:08:22 -0700267 public interface PageSwitchListener {
268 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700269 }
270
Winson Chung321e9ee2010-08-09 13:37:56 -0700271 public PagedView(Context context) {
272 this(context, null);
273 }
274
275 public PagedView(Context context, AttributeSet attrs) {
276 this(context, attrs, 0);
277 }
278
279 public PagedView(Context context, AttributeSet attrs, int defStyle) {
280 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700281
Adam Cohen9c4949e2010-10-05 12:27:22 -0700282 TypedArray a = context.obtainStyledAttributes(attrs,
283 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800284 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700285 if (mPageSpacing < 0) {
286 mAutoComputePageSpacing = mRecomputePageSpacing = true;
287 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800289 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700290 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800291 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800293 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700294 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800295 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700296 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700297 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700298 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700299 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700300 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700301 a.recycle();
302
Winson Chung321e9ee2010-08-09 13:37:56 -0700303 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700304 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700305 }
306
307 /**
308 * Initializes various states for this workspace.
309 */
Michael Jurka0142d492010-08-25 17:46:15 -0700310 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700311 mDirtyPageContent = new ArrayList<Boolean>();
312 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800313 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700314 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700315 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700316
317 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700318 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700319 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
320 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700321 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800322
Adam Cohen7d30a372013-07-01 17:03:59 -0700323 // Scale the fling-to-delete threshold by the density
324 mFlingToDeleteThresholdVelocity =
325 (int) (mFlingToDeleteThresholdVelocity * mDensity);
326
Adam Cohen265b9a62011-12-07 14:37:18 -0800327 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
328 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
329 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700330 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700331 }
332
Winson Chungd2be3812013-07-16 11:11:32 -0700333 protected void onAttachedToWindow() {
334 // Hook up the page indicator
335 ViewGroup parent = (ViewGroup) getParent();
336 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
337 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700338 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700339
340 ArrayList<Integer> markers = new ArrayList<Integer>();
341 for (int i = 0; i < getChildCount(); ++i) {
342 markers.add(getPageIndicatorMarker(i));
343 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700344
Winson Chungc58497e2013-09-03 17:48:37 -0700345 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700346 }
347 }
348
349 protected void onDetachedFromWindow() {
350 // Unhook the page indicator
351 mPageIndicator = null;
352 }
353
Adam Cohen7d30a372013-07-01 17:03:59 -0700354 void setDeleteDropTarget(View v) {
355 mDeleteDropTarget = v;
356 }
357
358 // Convenience methods to map points from self to parent and vice versa
359 float[] mapPointFromViewToParent(View v, float x, float y) {
360 mTmpPoint[0] = x;
361 mTmpPoint[1] = y;
362 v.getMatrix().mapPoints(mTmpPoint);
363 mTmpPoint[0] += v.getLeft();
364 mTmpPoint[1] += v.getTop();
365 return mTmpPoint;
366 }
367 float[] mapPointFromParentToView(View v, float x, float y) {
368 mTmpPoint[0] = x - v.getLeft();
369 mTmpPoint[1] = y - v.getTop();
370 v.getMatrix().invert(mTmpInvMatrix);
371 mTmpInvMatrix.mapPoints(mTmpPoint);
372 return mTmpPoint;
373 }
374
375 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700376 if (mDragView != null) {
377 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
378 (mDragViewBaselineLeft - mDragView.getLeft());
379 float y = mLastMotionY - mDownMotionY;
380 mDragView.setTranslationX(x);
381 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700382
Adam Cohenf358a4b2013-07-23 16:47:31 -0700383 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
384 + x + ", " + y);
385 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700386 }
387
388 public void setMinScale(float f) {
389 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700390 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700391 requestLayout();
392 }
393
394 @Override
395 public void setScaleX(float scaleX) {
396 super.setScaleX(scaleX);
397 if (isReordering(true)) {
398 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
399 mLastMotionX = p[0];
400 mLastMotionY = p[1];
401 updateDragViewTranslationDuringDrag();
402 }
403 }
404
405 // Convenience methods to get the actual width/height of the PagedView (since it is measured
406 // to be larger to account for the minimum possible scale)
407 int getViewportWidth() {
408 return mViewport.width();
409 }
410 int getViewportHeight() {
411 return mViewport.height();
412 }
413
414 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
415 // PagedView both horizontally and vertically
416 int getViewportOffsetX() {
417 return (getMeasuredWidth() - getViewportWidth()) / 2;
418 }
419
420 int getViewportOffsetY() {
421 return (getMeasuredHeight() - getViewportHeight()) / 2;
422 }
423
Adam Cohenedb40762013-07-18 16:45:45 -0700424 PageIndicator getPageIndicator() {
425 return mPageIndicator;
426 }
Winson Chung82dfe582013-07-26 15:07:49 -0700427 protected int getPageIndicatorMarker(int pageIndex) {
428 return R.layout.page_indicator_marker;
429 }
Adam Cohenedb40762013-07-18 16:45:45 -0700430
Winson Chung86f77532010-08-24 11:08:22 -0700431 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
432 mPageSwitchListener = pageSwitchListener;
433 if (mPageSwitchListener != null) {
434 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700435 }
436 }
437
438 /**
Winson Chung52aee602013-01-30 12:01:02 -0800439 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
440 */
441 public boolean isLayoutRtl() {
442 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
443 }
444
445 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700446 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
447 * out pages.
448 */
449 protected void setDataIsReady() {
450 mIsDataReady = true;
451 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700452
Winson Chungf0ea4d32011-06-06 14:27:16 -0700453 protected boolean isDataReady() {
454 return mIsDataReady;
455 }
456
457 /**
Winson Chung86f77532010-08-24 11:08:22 -0700458 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700459 *
Winson Chung86f77532010-08-24 11:08:22 -0700460 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700461 */
Winson Chung86f77532010-08-24 11:08:22 -0700462 int getCurrentPage() {
463 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700464 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700465
Winson Chung360e63f2012-04-27 13:48:05 -0700466 int getNextPage() {
467 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
468 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700469
Winson Chung86f77532010-08-24 11:08:22 -0700470 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700471 return getChildCount();
472 }
473
Winson Chung86f77532010-08-24 11:08:22 -0700474 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700475 return getChildAt(index);
476 }
477
Adam Cohenae4f1552011-10-20 00:15:42 -0700478 protected int indexToPage(int index) {
479 return index;
480 }
481
Winson Chung321e9ee2010-08-09 13:37:56 -0700482 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800483 * Updates the scroll of the current page immediately to its final scroll position. We use this
484 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
485 * the previous tab page.
486 */
487 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700488 // If the current page is invalid, just reset the scroll position to zero
489 int newX = 0;
490 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700491 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700492 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800493 scrollTo(newX, 0);
494 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800495 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800496 }
497
498 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700499 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
500 * ends, {@link #resumeScrolling()} should be called, along with
501 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
502 */
503 void pauseScrolling() {
504 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700505 }
506
507 /**
508 * Enables scrolling again.
509 * @see #pauseScrolling()
510 */
511 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700512 }
513 /**
Winson Chung86f77532010-08-24 11:08:22 -0700514 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700515 */
Winson Chung86f77532010-08-24 11:08:22 -0700516 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800517 if (!mScroller.isFinished()) {
518 mScroller.abortAnimation();
519 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800520 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
521 // the default
522 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800523 return;
524 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700525
Adam Cohene61a9a22013-06-11 15:45:31 -0700526 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700527 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700528 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700529 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800530 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700531 }
532
Winson Chung8c87cd82013-07-23 16:20:10 -0700533 /**
534 * The restore page will be set in place of the current page at the next (likely first)
535 * layout.
536 */
537 void setRestorePage(int restorePage) {
538 mRestorePage = restorePage;
539 }
540
Michael Jurka0142d492010-08-25 17:46:15 -0700541 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700542 if (mPageSwitchListener != null) {
543 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700544 }
Winson Chungd2be3812013-07-16 11:11:32 -0700545
546 // Update the page indicator (when we aren't reordering)
547 if (mPageIndicator != null && !isReordering(false)) {
548 mPageIndicator.setActiveMarker(getNextPage());
549 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700550 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800551 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700552 if (!mIsPageMoving) {
553 mIsPageMoving = true;
554 onPageBeginMoving();
555 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700556 }
557
Michael Jurkace7e05f2011-02-01 22:02:35 -0800558 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700559 if (mIsPageMoving) {
560 mIsPageMoving = false;
561 onPageEndMoving();
562 }
Michael Jurka0142d492010-08-25 17:46:15 -0700563 }
564
Adam Cohen26976d92011-03-22 15:33:33 -0700565 protected boolean isPageMoving() {
566 return mIsPageMoving;
567 }
568
Michael Jurka0142d492010-08-25 17:46:15 -0700569 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700570 protected void onPageBeginMoving() {
571 }
572
573 // a method that subclasses can override to add behavior
574 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700575 }
576
Winson Chung321e9ee2010-08-09 13:37:56 -0700577 /**
Winson Chung86f77532010-08-24 11:08:22 -0700578 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700579 *
580 * @param l The listener used to respond to long clicks.
581 */
582 @Override
583 public void setOnLongClickListener(OnLongClickListener l) {
584 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700585 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700586 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700587 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700588 }
Adam Cohen1697b792013-09-17 19:08:21 -0700589 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700590 }
591
592 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800593 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700594 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800595 }
596
597 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700598 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700599 // In free scroll mode, we clamp the scrollX
600 if (mFreeScroll) {
601 x = Math.min(x, mFreeScrollMaxScrollX);
602 x = Math.max(x, mFreeScrollMinScrollX);
603 }
604
Adam Cohen0ffac432013-07-10 11:19:26 -0700605 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800606 mUnboundedScrollX = x;
607
Adam Cohen0ffac432013-07-10 11:19:26 -0700608 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
609 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
610 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800611 super.scrollTo(0, y);
612 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700613 if (isRtl) {
614 overScroll(x - mMaxScrollX);
615 } else {
616 overScroll(x);
617 }
Adam Cohen68d73932010-11-15 10:50:58 -0800618 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700619 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800620 super.scrollTo(mMaxScrollX, y);
621 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700622 if (isRtl) {
623 overScroll(x);
624 } else {
625 overScroll(x - mMaxScrollX);
626 }
Adam Cohen68d73932010-11-15 10:50:58 -0800627 }
628 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800629 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800630 super.scrollTo(x, y);
631 }
632
Michael Jurka0142d492010-08-25 17:46:15 -0700633 mTouchX = x;
634 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700635
636 // Update the last motion events when scrolling
637 if (isReordering(true)) {
638 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
639 mLastMotionX = p[0];
640 mLastMotionY = p[1];
641 updateDragViewTranslationDuringDrag();
642 }
Michael Jurka0142d492010-08-25 17:46:15 -0700643 }
644
645 // we moved this functionality to a helper function so SmoothPagedView can reuse it
646 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700647 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700648 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700649 if (getScrollX() != mScroller.getCurrX()
650 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700651 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700652 float scaleX = mFreeScroll ? getScaleX() : 1f;
653 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
654 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700655 }
Michael Jurka0142d492010-08-25 17:46:15 -0700656 invalidate();
657 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700658 } else if (mNextPage != INVALID_PAGE) {
659 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700660 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700661 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700662
Winson Chung9c0565f2013-07-19 13:49:06 -0700663 // Load the associated pages if necessary
664 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
665 loadAssociatedPages(mCurrentPage);
666 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
667 }
668
Adam Cohen73aa9752010-11-24 16:26:58 -0800669 // We don't want to trigger a page end moving unless the page has settled
670 // and the user has stopped scrolling
671 if (mTouchState == TOUCH_STATE_REST) {
672 pageEndMoving();
673 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700674
Adam Cohen7d30a372013-07-01 17:03:59 -0700675 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700676 // Notify the user when the page changes
677 AccessibilityManager accessibilityManager = (AccessibilityManager)
678 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
679 if (accessibilityManager.isEnabled()) {
680 AccessibilityEvent ev =
681 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
682 ev.getText().add(getCurrentPageDescription());
683 sendAccessibilityEventUnchecked(ev);
684 }
Michael Jurka0142d492010-08-25 17:46:15 -0700685 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700686 }
Michael Jurka0142d492010-08-25 17:46:15 -0700687 return false;
688 }
689
690 @Override
691 public void computeScroll() {
692 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700693 }
694
Adam Cohen7d30a372013-07-01 17:03:59 -0700695 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
696 return mTopAlignPageWhenShrinkingForBouncer;
697 }
698
Adam Cohen96d30a12013-07-16 18:13:21 -0700699 public static class LayoutParams extends ViewGroup.LayoutParams {
700 public boolean isFullScreenPage = false;
701
702 /**
703 * {@inheritDoc}
704 */
705 public LayoutParams(int width, int height) {
706 super(width, height);
707 }
708
709 public LayoutParams(ViewGroup.LayoutParams source) {
710 super(source);
711 }
712 }
713
714 protected LayoutParams generateDefaultLayoutParams() {
715 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
716 }
717
Adam Cohenedb40762013-07-18 16:45:45 -0700718 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700719 LayoutParams lp = generateDefaultLayoutParams();
720 lp.isFullScreenPage = true;
721 super.addView(page, 0, lp);
722 }
723
Winson Chung321e9ee2010-08-09 13:37:56 -0700724 @Override
725 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700726 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700727 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
728 return;
729 }
730
Adam Cohen7d30a372013-07-01 17:03:59 -0700731 // We measure the dimensions of the PagedView to be larger than the pages so that when we
732 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700733 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
734 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
735 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700736 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700737 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
738 // viewport, we can be at most one and a half screens offset once we scale down
739 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700740 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Winson Chungc58497e2013-09-03 17:48:37 -0700741 int parentWidthSize, parentHeightSize;
742 int scaledWidthSize, scaledHeightSize;
743 if (mUseMinScale) {
744 parentWidthSize = (int) (1.5f * maxSize);
745 parentHeightSize = maxSize;
746 scaledWidthSize = (int) (parentWidthSize / mMinScale);
747 scaledHeightSize = (int) (parentHeightSize / mMinScale);
748 } else {
749 scaledWidthSize = widthSize;
750 scaledHeightSize = heightSize;
751 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700752 mViewport.set(0, 0, widthSize, heightSize);
753
754 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
755 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
756 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700757 }
758
Winson Chung8aad6102012-05-11 16:27:49 -0700759 // Return early if we aren't given a proper dimension
760 if (widthSize <= 0 || heightSize <= 0) {
761 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
762 return;
763 }
764
Adam Lesinski6b879f02010-11-04 16:15:23 -0700765 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
766 * of the All apps view on XLarge displays to not take up more space then it needs. Width
767 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
768 * each page to have the same width.
769 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700770 final int verticalPadding = getPaddingTop() + getPaddingBottom();
771 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700772
773 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700774 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700775 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700776 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
777 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
778 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
779 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700780 final int childCount = getChildCount();
781 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700782 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700783 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700784 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
785
786 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700787 int childHeightMode;
788 int childWidth;
789 int childHeight;
790
791 if (!lp.isFullScreenPage) {
792 if (lp.width == LayoutParams.WRAP_CONTENT) {
793 childWidthMode = MeasureSpec.AT_MOST;
794 } else {
795 childWidthMode = MeasureSpec.EXACTLY;
796 }
797
798 if (lp.height == LayoutParams.WRAP_CONTENT) {
799 childHeightMode = MeasureSpec.AT_MOST;
800 } else {
801 childHeightMode = MeasureSpec.EXACTLY;
802 }
803
804 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400805 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen96d30a12013-07-16 18:13:21 -0700806
Michael Jurka5f1c5092010-09-03 14:15:02 -0700807 } else {
808 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700809 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700810
Winson Chungc58497e2013-09-03 17:48:37 -0700811 if (mUseMinScale) {
812 childWidth = getViewportWidth();
813 childHeight = getViewportHeight();
814 } else {
815 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
816 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
817 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700818 }
819
820 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700821 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
822 final int childHeightMeasureSpec =
823 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700824 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700825 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700826 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700827
Winson Chunga128a7b2012-04-30 15:23:15 -0700828 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700829 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700830 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700831 // The gap between pages in the PagedView should be equal to the gap from the page
832 // to the edge of the screen (so it is not visible in the current screen). To
833 // account for unequal padding on each side of the paged view, we take the maximum
834 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700835 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700836 int spacing = Math.max(offset, widthSize - offset -
837 getChildAt(0).getMeasuredWidth());
838 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700839 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700840 }
841 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700842 }
843
Adam Cohen60b07122011-11-14 17:26:06 -0800844 public void setPageSpacing(int pageSpacing) {
845 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700846 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800847 }
848
Winson Chung321e9ee2010-08-09 13:37:56 -0700849 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700850 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700851 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700852 return;
853 }
854
Winson Chung785d2eb2011-04-14 16:08:02 -0700855 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700856 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700857
Adam Cohenedb40762013-07-18 16:45:45 -0700858 int screenWidth = getViewportWidth();
859
Adam Cohen7d30a372013-07-01 17:03:59 -0700860 int offsetX = getViewportOffsetX();
861 int offsetY = getViewportOffsetY();
862
863 // Update the viewport offsets
864 mViewport.offset(offsetX, offsetY);
865
Adam Cohen0ffac432013-07-10 11:19:26 -0700866 final boolean isRtl = isLayoutRtl();
867
868 final int startIndex = isRtl ? childCount - 1 : 0;
869 final int endIndex = isRtl ? -1 : childCount;
870 final int delta = isRtl ? -1 : 1;
871
Adam Cohen7d30a372013-07-01 17:03:59 -0700872 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700873 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
874
875 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
876 mPageScrolls = new int[getChildCount()];
877 }
878
Adam Cohen0ffac432013-07-10 11:19:26 -0700879 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700880 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700881 LayoutParams lp = (LayoutParams) child.getLayoutParams();
882 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700883 if (lp.isFullScreenPage) {
884 childTop = offsetY;
885 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400886 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700887 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400888 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700889 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700890 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700891
Winson Chung321e9ee2010-08-09 13:37:56 -0700892 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700893 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700894 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800895
Winson Chung785d2eb2011-04-14 16:08:02 -0700896 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700897 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800898 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700899
900 // We assume the left and right padding are equal, and hence center the pages
901 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700902 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700903 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
904
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700905 if (i != endIndex - delta) {
906 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
907 childLeft += childWidth + nextScrollOffset;
908 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700909 }
910 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700911
912 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
913 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800914 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700915 setHorizontalScrollBarEnabled(true);
916 mFirstLayout = false;
917 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700918
919 if (childCount > 0) {
920 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700921 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700922 } else {
923 mMaxScrollX = 0;
924 }
925
926 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
927 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700928 if (mRestorePage > -1) {
929 setCurrentPage(mRestorePage);
930 mRestorePage = -1;
931 } else {
932 setCurrentPage(getNextPage());
933 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700934 }
935 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700936
937 if (isReordering(true)) {
938 updateDragViewTranslationDuringDrag();
939 }
Winson Chunge3193b92010-09-10 11:44:42 -0700940 }
941
Adam Cohenf34bab52010-09-30 14:11:56 -0700942 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700943 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
944
945 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700946 for (int i = 0; i < getChildCount(); i++) {
947 View child = getChildAt(i);
948 if (child != null) {
949 float scrollProgress = getScrollProgress(screenCenter, child, i);
950 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800951 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700952 }
953 }
954 invalidate();
955 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700956 }
957
Winson Chungc58497e2013-09-03 17:48:37 -0700958 protected void enablePagedViewAnimations() {
959 mAllowPagedViewAnimations = true;
960
961 }
962 protected void disablePagedViewAnimations() {
963 mAllowPagedViewAnimations = false;
964 }
965
Winson Chunge3193b92010-09-10 11:44:42 -0700966 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700967 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700968 // Update the page indicator, we don't update the page indicator as we
969 // add/remove pages
970 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700971 int pageIndex = indexOfChild(child);
Winson Chungc58497e2013-09-03 17:48:37 -0700972 mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex),
973 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700974 }
975
Adam Cohen2591f6a2011-10-25 14:36:40 -0700976 // This ensures that when children are added, they get the correct transforms / alphas
977 // in accordance with any scroll effects.
978 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700979 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700980
Adam Cohen2591f6a2011-10-25 14:36:40 -0700981 invalidate();
982 }
983
Michael Jurka8b805b12012-04-18 14:23:14 -0700984 @Override
985 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700986 mForceScreenScrolled = true;
987 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700988 }
989
Winson Chungd2be3812013-07-16 11:11:32 -0700990 private void removeMarkerForView(int index) {
991 // Update the page indicator, we don't update the page indicator as we
992 // add/remove pages
993 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -0700994 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700995 }
996 }
997
998 @Override
999 public void removeView(View v) {
1000 // XXX: We should find a better way to hook into this before the view
1001 // gets removed form its parent...
1002 removeMarkerForView(indexOfChild(v));
1003 super.removeView(v);
1004 }
1005 @Override
1006 public void removeViewInLayout(View v) {
1007 // XXX: We should find a better way to hook into this before the view
1008 // gets removed form its parent...
1009 removeMarkerForView(indexOfChild(v));
1010 super.removeViewInLayout(v);
1011 }
1012 @Override
1013 public void removeViewAt(int index) {
1014 // XXX: We should find a better way to hook into this before the view
1015 // gets removed form its parent...
1016 removeViewAt(index);
1017 super.removeViewAt(index);
1018 }
1019 @Override
1020 public void removeAllViewsInLayout() {
1021 // Update the page indicator, we don't update the page indicator as we
1022 // add/remove pages
1023 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001024 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001025 }
1026
1027 super.removeAllViewsInLayout();
1028 }
1029
Adam Cohen73894962011-10-31 13:17:17 -07001030 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001031 if (index < 0 || index > getChildCount() - 1) return 0;
1032
Adam Cohen0ffac432013-07-10 11:19:26 -07001033 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -07001034
Adam Cohenf698c6e2013-07-17 18:44:25 -07001035 if (isRtl) index = getChildCount() - index - 1;
1036 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001037
Adam Cohenf698c6e2013-07-17 18:44:25 -07001038 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001039 }
1040
Adam Cohenf358a4b2013-07-23 16:47:31 -07001041 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001042 range[0] = 0;
1043 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001044 }
1045
Michael Jurkadde558b2011-11-09 22:09:06 -08001046 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001047 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001048 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001049
Michael Jurkac4fb9172010-09-02 17:19:20 -07001050 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001051 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001052 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001053 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001054
Winson Chungc9ca2982013-07-19 12:07:38 -07001055 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1056 View currPage = getPageAt(leftScreen);
1057
1058 // Check if the right edge of the page is in the viewport
1059 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001060 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001061 if (mTmpIntPoint[0] < 0) {
1062 break;
1063 }
1064 }
1065 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1066 View currPage = getPageAt(rightScreen);
1067
1068 // Check if the left edge of the page is in the viewport
1069 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001070 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001071 if (mTmpIntPoint[0] >= viewportWidth) {
1072 break;
1073 }
1074 }
1075 range[0] = Math.max(0, leftScreen);
1076 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001077 } else {
1078 range[0] = -1;
1079 range[1] = -1;
1080 }
1081 }
1082
Michael Jurka920d7f42012-05-14 16:29:55 -07001083 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001084 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001085 }
1086
Michael Jurkadde558b2011-11-09 22:09:06 -08001087 @Override
1088 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001089 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001090 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1091 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001092 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001093
1094 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001095 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1096 // set it for the next frame
1097 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001098 screenScrolled(screenCenter);
1099 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001100 }
1101
1102 // Find out which screens are visible; as an optimization we only call draw on them
1103 final int pageCount = getChildCount();
1104 if (pageCount > 0) {
1105 getVisiblePages(mTempVisiblePagesRange);
1106 final int leftScreen = mTempVisiblePagesRange[0];
1107 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001108 if (leftScreen != -1 && rightScreen != -1) {
1109 final long drawingTime = getDrawingTime();
1110 // Clip to the bounds
1111 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001112 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1113 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001114
Adam Cohen7d30a372013-07-01 17:03:59 -07001115 // Draw all the children, leaving the drag view for last
1116 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001117 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001118 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001119 if (mForceDrawAllChildrenNextFrame ||
1120 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001121 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001122 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001123 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001124 // Draw the drag view on top (if there is one)
1125 if (mDragView != null) {
1126 drawChild(canvas, mDragView, drawingTime);
1127 }
1128
Michael Jurka5e368ff2012-05-14 23:13:15 -07001129 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001130 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001131 }
Michael Jurka0142d492010-08-25 17:46:15 -07001132 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001133 }
1134
1135 @Override
1136 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001137 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001138 if (page != mCurrentPage || !mScroller.isFinished()) {
1139 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001140 return true;
1141 }
1142 return false;
1143 }
1144
1145 @Override
1146 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001147 int focusablePage;
1148 if (mNextPage != INVALID_PAGE) {
1149 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001150 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001151 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001152 }
Winson Chung86f77532010-08-24 11:08:22 -07001153 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001154 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001155 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001156 }
1157 return false;
1158 }
1159
1160 @Override
1161 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001162 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001163 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001164 if (getCurrentPage() > 0) {
1165 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001166 return true;
1167 }
1168 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001169 if (getCurrentPage() < getPageCount() - 1) {
1170 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001171 return true;
1172 }
1173 }
1174 return super.dispatchUnhandledMove(focused, direction);
1175 }
1176
1177 @Override
1178 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001179 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001180 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001181 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001182 }
1183 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001184 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001185 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001186 }
1187 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001188 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001189 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001190 }
1191 }
1192 }
1193
1194 /**
1195 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001196 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001197 *
Winson Chung86f77532010-08-24 11:08:22 -07001198 * This happens when live folders requery, and if they're off page, they
1199 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001200 */
1201 @Override
1202 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001203 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001204 View v = focused;
1205 while (true) {
1206 if (v == current) {
1207 super.focusableViewAvailable(focused);
1208 return;
1209 }
1210 if (v == this) {
1211 return;
1212 }
1213 ViewParent parent = v.getParent();
1214 if (parent instanceof View) {
1215 v = (View)v.getParent();
1216 } else {
1217 return;
1218 }
1219 }
1220 }
1221
1222 /**
1223 * {@inheritDoc}
1224 */
1225 @Override
1226 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1227 if (disallowIntercept) {
1228 // We need to make sure to cancel our long press if
1229 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001230 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001231 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001232 }
1233 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1234 }
1235
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001236 /**
1237 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1238 */
1239 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001240 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001241 if (isLayoutRtl()) {
1242 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001243 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001244 }
Adam Cohenedb40762013-07-18 16:45:45 -07001245 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001246 }
1247
1248 /**
1249 * Return true if a tap at (x, y) should trigger a flip to the next page.
1250 */
1251 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001252 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001253 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001254 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001255 }
1256 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001257 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001258 }
Winson Chung52aee602013-01-30 12:01:02 -08001259
Adam Cohen7d30a372013-07-01 17:03:59 -07001260 /** Returns whether x and y originated within the buffered viewport */
1261 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1262 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1263 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1264 return mTmpRect.contains(x, y);
1265 }
1266
Winson Chung321e9ee2010-08-09 13:37:56 -07001267 @Override
1268 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001269 if (DISABLE_TOUCH_INTERACTION) {
1270 return false;
1271 }
1272
Winson Chung321e9ee2010-08-09 13:37:56 -07001273 /*
1274 * This method JUST determines whether we want to intercept the motion.
1275 * If we return true, onTouchEvent will be called and we do the actual
1276 * scrolling there.
1277 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001278 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001279
Winson Chung45e1d6e2010-11-09 17:19:49 -08001280 // Skip touch handling if there are no pages to swipe
1281 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1282
Winson Chung321e9ee2010-08-09 13:37:56 -07001283 /*
1284 * Shortcut the most recurring case: the user is in the dragging
1285 * state and he is moving his finger. We want to intercept this
1286 * motion.
1287 */
1288 final int action = ev.getAction();
1289 if ((action == MotionEvent.ACTION_MOVE) &&
1290 (mTouchState == TOUCH_STATE_SCROLLING)) {
1291 return true;
1292 }
1293
Winson Chung321e9ee2010-08-09 13:37:56 -07001294 switch (action & MotionEvent.ACTION_MASK) {
1295 case MotionEvent.ACTION_MOVE: {
1296 /*
1297 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1298 * whether the user has moved far enough from his original down touch.
1299 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001300 if (mActivePointerId != INVALID_POINTER) {
1301 determineScrollingStart(ev);
1302 break;
1303 }
1304 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1305 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1306 // i.e. fall through to the next case (don't break)
1307 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1308 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001309 }
1310
1311 case MotionEvent.ACTION_DOWN: {
1312 final float x = ev.getX();
1313 final float y = ev.getY();
1314 // Remember location of down touch
1315 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001316 mDownMotionY = y;
1317 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001318 mLastMotionX = x;
1319 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001320 float[] p = mapPointFromViewToParent(this, x, y);
1321 mParentDownMotionX = p[0];
1322 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001323 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001324 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001325 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001326
Winson Chung321e9ee2010-08-09 13:37:56 -07001327 /*
1328 * If being flinged and user touches the screen, initiate drag;
1329 * otherwise don't. mScroller.isFinished should be false when
1330 * being flinged.
1331 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001332 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001333 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1334 if (finishedScrolling) {
1335 mTouchState = TOUCH_STATE_REST;
1336 mScroller.abortAnimation();
1337 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001338 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1339 mTouchState = TOUCH_STATE_SCROLLING;
1340 } else {
1341 mTouchState = TOUCH_STATE_REST;
1342 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001343 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001344
Winson Chung86f77532010-08-24 11:08:22 -07001345 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001346 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001347 if (!DISABLE_TOUCH_SIDE_PAGES) {
1348 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1349 if (getChildCount() > 0) {
1350 if (hitsPreviousPage(x, y)) {
1351 mTouchState = TOUCH_STATE_PREV_PAGE;
1352 } else if (hitsNextPage(x, y)) {
1353 mTouchState = TOUCH_STATE_NEXT_PAGE;
1354 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 }
1356 }
1357 }
1358 break;
1359 }
1360
Winson Chung321e9ee2010-08-09 13:37:56 -07001361 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001362 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001363 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001364 break;
1365
1366 case MotionEvent.ACTION_POINTER_UP:
1367 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001368 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001369 break;
1370 }
1371
1372 /*
1373 * The only time we want to intercept motion events is if we are in the
1374 * drag mode.
1375 */
1376 return mTouchState != TOUCH_STATE_REST;
1377 }
1378
Adam Cohenf8d28232011-02-01 21:47:00 -08001379 protected void determineScrollingStart(MotionEvent ev) {
1380 determineScrollingStart(ev, 1.0f);
1381 }
1382
Winson Chung321e9ee2010-08-09 13:37:56 -07001383 /*
1384 * Determines if we should change the touch state to start scrolling after the
1385 * user moves their touch point too far.
1386 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001387 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001388 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001389 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001390 if (pointerIndex == -1) return;
1391
1392 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001393 final float x = ev.getX(pointerIndex);
1394 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001395 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1396
Winson Chung321e9ee2010-08-09 13:37:56 -07001397 final int xDiff = (int) Math.abs(x - mLastMotionX);
1398 final int yDiff = (int) Math.abs(y - mLastMotionY);
1399
Adam Cohenf8d28232011-02-01 21:47:00 -08001400 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001401 boolean xPaged = xDiff > mPagingTouchSlop;
1402 boolean xMoved = xDiff > touchSlop;
1403 boolean yMoved = yDiff > touchSlop;
1404
Adam Cohenf8d28232011-02-01 21:47:00 -08001405 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001406 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001407 // Scroll if the user moved far enough along the X axis
1408 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001409 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001410 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001411 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001412 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001413 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1414 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001415 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001416 }
1417 }
1418
Adam Cohen7d30a372013-07-01 17:03:59 -07001419 protected float getMaxScrollProgress() {
1420 return 1.0f;
1421 }
1422
Adam Cohenf8d28232011-02-01 21:47:00 -08001423 protected void cancelCurrentPageLongPress() {
1424 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001425 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001426 // Try canceling the long press. It could also have been scheduled
1427 // by a distant descendant, so use the mAllowLongPress flag to block
1428 // everything
1429 final View currentPage = getPageAt(mCurrentPage);
1430 if (currentPage != null) {
1431 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001432 }
1433 }
1434 }
1435
Adam Cohen7d30a372013-07-01 17:03:59 -07001436 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1437 final int halfScreenSize = getViewportWidth() / 2;
1438
1439 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1440 screenCenter = Math.max(halfScreenSize, screenCenter);
1441
1442 return getScrollProgress(screenCenter, v, page);
1443 }
1444
Adam Cohenb5ba0972011-09-07 18:02:31 -07001445 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001446 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001447
Adam Cohen96d30a12013-07-16 18:13:21 -07001448 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001449 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001450
1451 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001452 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1453 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001454 return scrollProgress;
1455 }
1456
Adam Cohenedb40762013-07-18 16:45:45 -07001457 public int getScrollForPage(int index) {
1458 if (mPageScrolls == null || index >= mPageScrolls.length) {
1459 return 0;
1460 } else {
1461 return mPageScrolls[index];
1462 }
1463 }
1464
Adam Cohene0f66b52010-11-23 15:06:07 -08001465 // This curve determines how the effect of scrolling over the limits of the page dimishes
1466 // as the user pulls further and further from the bounds
1467 private float overScrollInfluenceCurve(float f) {
1468 f -= 1.0f;
1469 return f * f * f + 1.0f;
1470 }
1471
Adam Cohenb5ba0972011-09-07 18:02:31 -07001472 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001473 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001474
1475 // We want to reach the max over scroll effect when the user has
1476 // over scrolled half the size of the screen
1477 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1478
1479 if (f == 0) return;
1480
1481 // Clamp this factor, f, to -1 < f < 1
1482 if (Math.abs(f) >= 1) {
1483 f /= Math.abs(f);
1484 }
1485
1486 int overScrollAmount = (int) Math.round(f * screenSize);
1487 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001488 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001489 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001490 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001491 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001492 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001493 }
1494 invalidate();
1495 }
1496
1497 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001498 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001499
1500 float f = (amount / screenSize);
1501
1502 if (f == 0) return;
1503 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1504
Adam Cohen7bfc9792011-01-28 13:52:37 -08001505 // Clamp this factor, f, to -1 < f < 1
1506 if (Math.abs(f) >= 1) {
1507 f /= Math.abs(f);
1508 }
1509
Adam Cohene0f66b52010-11-23 15:06:07 -08001510 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001511 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001512 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001513 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001514 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001515 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001516 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001517 }
1518 invalidate();
1519 }
1520
Adam Cohenb5ba0972011-09-07 18:02:31 -07001521 protected void overScroll(float amount) {
1522 dampedOverScroll(amount);
1523 }
1524
Michael Jurkac5b262c2011-01-12 20:24:50 -08001525 protected float maxOverScroll() {
1526 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001527 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001528 float f = 1.0f;
1529 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1530 return OVERSCROLL_DAMP_FACTOR * f;
1531 }
1532
Adam Cohenf358a4b2013-07-23 16:47:31 -07001533 protected void enableFreeScroll() {
1534 setEnableFreeScroll(true, -1);
1535 }
1536
1537 protected void disableFreeScroll(int snapPage) {
1538 setEnableFreeScroll(false, snapPage);
1539 }
1540
1541 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1542 mFreeScroll = freeScroll;
1543
1544 if (snapPage == -1) {
1545 snapPage = getPageNearestToCenterOfScreen();
1546 }
1547
1548 getOverviewModePages(mTempVisiblePagesRange);
1549 if (!mFreeScroll) {
1550 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001551 } else {
1552 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1553 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1554
Adam Cohenf358a4b2013-07-23 16:47:31 -07001555 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1556 setCurrentPage(mTempVisiblePagesRange[0]);
1557 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1558 setCurrentPage(mTempVisiblePagesRange[1]);
1559 }
1560 }
1561
1562 setEnableOverscroll(!freeScroll);
1563 }
1564
1565 private void setEnableOverscroll(boolean enable) {
1566 mAllowOverScroll = enable;
1567 }
1568
1569 int getNearestHoverOverPageIndex() {
1570 if (mDragView != null) {
1571 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1572 + mDragView.getTranslationX());
1573 getOverviewModePages(mTempVisiblePagesRange);
1574 int minDistance = Integer.MAX_VALUE;
1575 int minIndex = indexOfChild(mDragView);
1576 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1577 View page = getPageAt(i);
1578 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1579 int d = Math.abs(dragX - pageX);
1580 if (d < minDistance) {
1581 minIndex = i;
1582 minDistance = d;
1583 }
1584 }
1585 return minIndex;
1586 }
1587 return -1;
1588 }
1589
Winson Chung321e9ee2010-08-09 13:37:56 -07001590 @Override
1591 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001592 if (DISABLE_TOUCH_INTERACTION) {
1593 return false;
1594 }
1595
Adam Cohen1697b792013-09-17 19:08:21 -07001596 super.onTouchEvent(ev);
1597
Winson Chung45e1d6e2010-11-09 17:19:49 -08001598 // Skip touch handling if there are no pages to swipe
1599 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1600
Michael Jurkab8f06722010-10-10 15:58:46 -07001601 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001602
1603 final int action = ev.getAction();
1604
1605 switch (action & MotionEvent.ACTION_MASK) {
1606 case MotionEvent.ACTION_DOWN:
1607 /*
1608 * If being flinged and user touches, stop the fling. isFinished
1609 * will be false if being flinged.
1610 */
1611 if (!mScroller.isFinished()) {
1612 mScroller.abortAnimation();
1613 }
1614
1615 // Remember where the motion event started
1616 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001617 mDownMotionY = mLastMotionY = ev.getY();
1618 mDownScrollX = getScrollX();
1619 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1620 mParentDownMotionX = p[0];
1621 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001622 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001623 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001624 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001625
Michael Jurka0142d492010-08-25 17:46:15 -07001626 if (mTouchState == TOUCH_STATE_SCROLLING) {
1627 pageBeginMoving();
1628 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001629 break;
1630
1631 case MotionEvent.ACTION_MOVE:
1632 if (mTouchState == TOUCH_STATE_SCROLLING) {
1633 // Scroll to follow the motion event
1634 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001635
1636 if (pointerIndex == -1) return true;
1637
Winson Chung321e9ee2010-08-09 13:37:56 -07001638 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001639 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001640
Adam Cohenaefd4e12011-02-14 16:39:38 -08001641 mTotalMotionX += Math.abs(deltaX);
1642
Winson Chungc0844aa2011-02-02 15:25:58 -08001643 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1644 // keep the remainder because we are actually testing if we've moved from the last
1645 // scrolled position (which is discrete).
1646 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001647 mTouchX += deltaX;
1648 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1649 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001650 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001651 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001652 } else {
1653 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001654 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001655 mLastMotionX = x;
1656 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001657 } else {
1658 awakenScrollBars();
1659 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001660 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1661 // Update the last motion position
1662 mLastMotionX = ev.getX();
1663 mLastMotionY = ev.getY();
1664
1665 // Update the parent down so that our zoom animations take this new movement into
1666 // account
1667 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1668 mParentDownMotionX = pt[0];
1669 mParentDownMotionY = pt[1];
1670 updateDragViewTranslationDuringDrag();
1671
1672 // Find the closest page to the touch point
1673 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001674
1675 // Change the drag view if we are hovering over the drop target
1676 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1677 (int) mParentDownMotionX, (int) mParentDownMotionY);
1678 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1679
Adam Cohen7d30a372013-07-01 17:03:59 -07001680 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1681 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1682 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1683 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1684
Adam Cohenf358a4b2013-07-23 16:47:31 -07001685 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1686 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1687 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001688 mTempVisiblePagesRange[0] = 0;
1689 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001690 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001691 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1692 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1693 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1694 mSidePageHoverIndex = pageUnderPointIndex;
1695 mSidePageHoverRunnable = new Runnable() {
1696 @Override
1697 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001698 // Setup the scroll to the correct page before we swap the views
1699 snapToPage(pageUnderPointIndex);
1700
1701 // For each of the pages between the paged view and the drag view,
1702 // animate them from the previous position to the new position in
1703 // the layout (as a result of the drag view moving in the layout)
1704 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1705 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1706 dragViewIndex + 1 : pageUnderPointIndex;
1707 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1708 dragViewIndex - 1 : pageUnderPointIndex;
1709 for (int i = lowerIndex; i <= upperIndex; ++i) {
1710 View v = getChildAt(i);
1711 // dragViewIndex < pageUnderPointIndex, so after we remove the
1712 // drag view all subsequent views to pageUnderPointIndex will
1713 // shift down.
1714 int oldX = getViewportOffsetX() + getChildOffset(i);
1715 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1716
1717 // Animate the view translation from its old position to its new
1718 // position
1719 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1720 if (anim != null) {
1721 anim.cancel();
1722 }
1723
1724 v.setTranslationX(oldX - newX);
1725 anim = new AnimatorSet();
1726 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1727 anim.playTogether(
1728 ObjectAnimator.ofFloat(v, "translationX", 0f));
1729 anim.start();
1730 v.setTag(anim);
1731 }
1732
1733 removeView(mDragView);
1734 onRemoveView(mDragView, false);
1735 addView(mDragView, pageUnderPointIndex);
1736 onAddView(mDragView, pageUnderPointIndex);
1737 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001738 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001739 }
1740 };
1741 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1742 }
1743 } else {
1744 removeCallbacks(mSidePageHoverRunnable);
1745 mSidePageHoverIndex = -1;
1746 }
Adam Cohen564976a2010-10-13 18:52:07 -07001747 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001748 determineScrollingStart(ev);
1749 }
1750 break;
1751
1752 case MotionEvent.ACTION_UP:
1753 if (mTouchState == TOUCH_STATE_SCROLLING) {
1754 final int activePointerId = mActivePointerId;
1755 final int pointerIndex = ev.findPointerIndex(activePointerId);
1756 final float x = ev.getX(pointerIndex);
1757 final VelocityTracker velocityTracker = mVelocityTracker;
1758 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1759 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001760 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001761 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001762 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1763 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001764
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001765 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1766
Adam Cohen00481b32011-11-18 12:03:48 -08001767 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001768 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001769
Adam Cohenf358a4b2013-07-23 16:47:31 -07001770 if (!mFreeScroll) {
1771 // In the case that the page is moved far to one direction and then is flung
1772 // in the opposite direction, we use a threshold to determine whether we should
1773 // just return to the starting page, or if we should skip one further.
1774 boolean returnToOriginalPage = false;
1775 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1776 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1777 returnToOriginalPage = true;
1778 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001779
Adam Cohenf358a4b2013-07-23 16:47:31 -07001780 int finalPage;
1781 // We give flings precedence over large moves, which is why we short-circuit our
1782 // test for a large move if a fling has been registered. That is, a large
1783 // move to the left and fling to the right will register as a fling to the right.
1784 final boolean isRtl = isLayoutRtl();
1785 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1786 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1787 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1788 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1789 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1790 snapToPageWithVelocity(finalPage, velocityX);
1791 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1792 (isFling && isVelocityXLeft)) &&
1793 mCurrentPage < getChildCount() - 1) {
1794 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1795 snapToPageWithVelocity(finalPage, velocityX);
1796 } else {
1797 snapToDestination();
1798 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1799 // at this point we have not moved beyond the touch slop
1800 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1801 // we can just page
1802 int nextPage = Math.max(0, mCurrentPage - 1);
1803 if (nextPage != mCurrentPage) {
1804 snapToPage(nextPage);
1805 } else {
1806 snapToDestination();
1807 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001808 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001809 if (!mScroller.isFinished()) {
1810 mScroller.abortAnimation();
1811 }
1812
1813 float scaleX = getScaleX();
1814 int vX = (int) (-velocityX * scaleX);
1815 int initialScrollX = (int) (getScrollX() * scaleX);
1816
1817 mScroller.fling(initialScrollX,
1818 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1819 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001820 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001821 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001822 // at this point we have not moved beyond the touch slop
1823 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1824 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001825 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1826 if (nextPage != mCurrentPage) {
1827 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001828 } else {
1829 snapToDestination();
1830 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001831 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1832 // Update the last motion position
1833 mLastMotionX = ev.getX();
1834 mLastMotionY = ev.getY();
1835
1836 // Update the parent down so that our zoom animations take this new movement into
1837 // account
1838 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1839 mParentDownMotionX = pt[0];
1840 mParentDownMotionY = pt[1];
1841 updateDragViewTranslationDuringDrag();
1842 boolean handledFling = false;
1843 if (!DISABLE_FLING_TO_DELETE) {
1844 // Check the velocity and see if we are flinging-to-delete
1845 PointF flingToDeleteVector = isFlingingToDelete();
1846 if (flingToDeleteVector != null) {
1847 onFlingToDelete(flingToDeleteVector);
1848 handledFling = true;
1849 }
1850 }
1851 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1852 (int) mParentDownMotionY)) {
1853 onDropToDelete();
1854 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001855 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001856 if (!mCancelTap) {
1857 onUnhandledTap(ev);
1858 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001859 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001860
1861 // Remove the callback to wait for the side page hover timeout
1862 removeCallbacks(mSidePageHoverRunnable);
1863 // End any intermediate reordering states
1864 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001865 break;
1866
1867 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001868 if (mTouchState == TOUCH_STATE_SCROLLING) {
1869 snapToDestination();
1870 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001871 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001872 break;
1873
1874 case MotionEvent.ACTION_POINTER_UP:
1875 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001876 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001877 break;
1878 }
1879
1880 return true;
1881 }
1882
Adam Cohen7d30a372013-07-01 17:03:59 -07001883 public void onFlingToDelete(View v) {}
1884 public void onRemoveView(View v, boolean deletePermanently) {}
1885 public void onRemoveViewAnimationCompleted() {}
1886 public void onAddView(View v, int index) {}
1887
1888 private void resetTouchState() {
1889 releaseVelocityTracker();
1890 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001891 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001892 mTouchState = TOUCH_STATE_REST;
1893 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001894 }
1895
Adam Cohen1697b792013-09-17 19:08:21 -07001896 protected void onUnhandledTap(MotionEvent ev) {
1897 ((Launcher) getContext()).onClick(this);
1898 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001899
Winson Chung185d7162011-02-28 13:47:29 -08001900 @Override
1901 public boolean onGenericMotionEvent(MotionEvent event) {
1902 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1903 switch (event.getAction()) {
1904 case MotionEvent.ACTION_SCROLL: {
1905 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1906 final float vscroll;
1907 final float hscroll;
1908 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1909 vscroll = 0;
1910 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1911 } else {
1912 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1913 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1914 }
1915 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001916 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1917 : (hscroll > 0 || vscroll > 0);
1918 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001919 scrollRight();
1920 } else {
1921 scrollLeft();
1922 }
1923 return true;
1924 }
1925 }
1926 }
1927 }
1928 return super.onGenericMotionEvent(event);
1929 }
1930
Michael Jurkab8f06722010-10-10 15:58:46 -07001931 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1932 if (mVelocityTracker == null) {
1933 mVelocityTracker = VelocityTracker.obtain();
1934 }
1935 mVelocityTracker.addMovement(ev);
1936 }
1937
1938 private void releaseVelocityTracker() {
1939 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001940 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001941 mVelocityTracker.recycle();
1942 mVelocityTracker = null;
1943 }
1944 }
1945
Winson Chung321e9ee2010-08-09 13:37:56 -07001946 private void onSecondaryPointerUp(MotionEvent ev) {
1947 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1948 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1949 final int pointerId = ev.getPointerId(pointerIndex);
1950 if (pointerId == mActivePointerId) {
1951 // This was our active pointer going up. Choose a new
1952 // active pointer and adjust accordingly.
1953 // TODO: Make this decision more intelligent.
1954 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1955 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1956 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001957 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001958 mActivePointerId = ev.getPointerId(newPointerIndex);
1959 if (mVelocityTracker != null) {
1960 mVelocityTracker.clear();
1961 }
1962 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001963 }
1964
Winson Chung321e9ee2010-08-09 13:37:56 -07001965 @Override
1966 public void requestChildFocus(View child, View focused) {
1967 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001968 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001969 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001970 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001971 }
1972 }
1973
Winson Chung1908d072011-02-24 18:09:44 -08001974 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001975 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001976 }
1977
Adam Cohen7d30a372013-07-01 17:03:59 -07001978 int getPageNearestToPoint(float x) {
1979 int index = 0;
1980 for (int i = 0; i < getChildCount(); ++i) {
1981 if (x < getChildAt(i).getRight() - getScrollX()) {
1982 return index;
1983 } else {
1984 index++;
1985 }
1986 }
1987 return Math.min(index, getChildCount() - 1);
1988 }
1989
Adam Cohend19d3ca2010-09-15 14:43:42 -07001990 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001991 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001992 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001993 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001994 final int childCount = getChildCount();
1995 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001996 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001997 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001998 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001999 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002000 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2001 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2002 minDistanceFromScreenCenter = distanceFromScreenCenter;
2003 minDistanceFromScreenCenterIndex = i;
2004 }
2005 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002006 return minDistanceFromScreenCenterIndex;
2007 }
2008
2009 protected void snapToDestination() {
2010 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002011 }
2012
Adam Cohene0f66b52010-11-23 15:06:07 -08002013 private static class ScrollInterpolator implements Interpolator {
2014 public ScrollInterpolator() {
2015 }
2016
2017 public float getInterpolation(float t) {
2018 t -= 1.0f;
2019 return t*t*t*t*t + 1;
2020 }
2021 }
2022
2023 // We want the duration of the page snap animation to be influenced by the distance that
2024 // the screen has to travel, however, we don't want this duration to be effected in a
2025 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2026 // of travel has on the overall snap duration.
2027 float distanceInfluenceForSnapDuration(float f) {
2028 f -= 0.5f; // center the values about 0.
2029 f *= 0.3f * Math.PI / 2.0f;
2030 return (float) Math.sin(f);
2031 }
2032
Michael Jurka0142d492010-08-25 17:46:15 -07002033 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002034 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002035 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002036
Adam Cohenedb40762013-07-18 16:45:45 -07002037 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002038 int delta = newX - mUnboundedScrollX;
2039 int duration = 0;
2040
Adam Cohen265b9a62011-12-07 14:37:18 -08002041 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002042 // If the velocity is low enough, then treat this more as an automatic page advance
2043 // as opposed to an apparent physical response to flinging
2044 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2045 return;
2046 }
2047
2048 // Here we compute a "distance" that will be used in the computation of the overall
2049 // snap duration. This is a function of the actual distance that needs to be traveled;
2050 // we keep this value close to half screen size in order to reduce the variance in snap
2051 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002052 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002053 float distance = halfScreenSize + halfScreenSize *
2054 distanceInfluenceForSnapDuration(distanceRatio);
2055
2056 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002057 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002058
2059 // we want the page's snap velocity to approximately match the velocity at which the
2060 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002061 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2062 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002063
2064 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002065 }
2066
2067 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002068 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002069 }
2070
Adam Cohen7d30a372013-07-01 17:03:59 -07002071 protected void snapToPageImmediately(int whichPage) {
2072 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2073 }
2074
Michael Jurka0142d492010-08-25 17:46:15 -07002075 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002076 snapToPage(whichPage, duration, false);
2077 }
2078
2079 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002080 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002081
Adam Cohenedb40762013-07-18 16:45:45 -07002082 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002083 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002084 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002085 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002086 }
2087
2088 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002089 snapToPage(whichPage, delta, duration, false);
2090 }
Michael Jurka0142d492010-08-25 17:46:15 -07002091
Adam Cohen7d30a372013-07-01 17:03:59 -07002092 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2093 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002094 View focusedChild = getFocusedChild();
2095 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002096 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002097 focusedChild.clearFocus();
2098 }
2099
2100 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002101 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002102 if (immediate) {
2103 duration = 0;
2104 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002105 duration = Math.abs(delta);
2106 }
2107
Adam Cohenf358a4b2013-07-23 16:47:31 -07002108 if (!mScroller.isFinished()) {
2109 mScroller.abortAnimation();
2110 }
Adam Cohen68d73932010-11-15 10:50:58 -08002111 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002112
Michael Jurka0142d492010-08-25 17:46:15 -07002113 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002114
2115 // Trigger a compute() to finish switching pages if necessary
2116 if (immediate) {
2117 computeScroll();
2118 }
2119
Winson Chung9c0565f2013-07-19 13:49:06 -07002120 // Defer loading associated pages until the scroll settles
2121 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2122
Adam Cohen7d30a372013-07-01 17:03:59 -07002123 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002124 invalidate();
2125 }
2126
Winson Chung321e9ee2010-08-09 13:37:56 -07002127 public void scrollLeft() {
2128 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002129 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002130 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002131 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002132 }
2133 }
2134
2135 public void scrollRight() {
2136 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002137 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002138 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002139 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002140 }
2141 }
2142
Winson Chung86f77532010-08-24 11:08:22 -07002143 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002144 int result = -1;
2145 if (v != null) {
2146 ViewParent vp = v.getParent();
2147 int count = getChildCount();
2148 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002149 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002150 return i;
2151 }
2152 }
2153 }
2154 return result;
2155 }
2156
2157 /**
2158 * @return True is long presses are still allowed for the current touch
2159 */
2160 public boolean allowLongPress() {
2161 return mAllowLongPress;
2162 }
2163
Adam Cohendbdff6b2013-09-18 19:09:15 -07002164 @Override
2165 public boolean performLongClick() {
2166 mCancelTap = true;
2167 return super.performLongClick();
2168 }
2169
Michael Jurka0142d492010-08-25 17:46:15 -07002170 /**
2171 * Set true to allow long-press events to be triggered, usually checked by
2172 * {@link Launcher} to accept or block dpad-initiated long-presses.
2173 */
2174 public void setAllowLongPress(boolean allowLongPress) {
2175 mAllowLongPress = allowLongPress;
2176 }
2177
Winson Chung321e9ee2010-08-09 13:37:56 -07002178 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002179 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002180
2181 SavedState(Parcelable superState) {
2182 super(superState);
2183 }
2184
2185 private SavedState(Parcel in) {
2186 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002187 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002188 }
2189
2190 @Override
2191 public void writeToParcel(Parcel out, int flags) {
2192 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002193 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002194 }
2195
2196 public static final Parcelable.Creator<SavedState> CREATOR =
2197 new Parcelable.Creator<SavedState>() {
2198 public SavedState createFromParcel(Parcel in) {
2199 return new SavedState(in);
2200 }
2201
2202 public SavedState[] newArray(int size) {
2203 return new SavedState[size];
2204 }
2205 };
2206 }
2207
Winson Chungf314b0e2011-08-16 11:54:27 -07002208 protected void loadAssociatedPages(int page) {
2209 loadAssociatedPages(page, false);
2210 }
2211 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002212 if (mContentIsRefreshable) {
2213 final int count = getChildCount();
2214 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002215 int lowerPageBound = getAssociatedLowerPageBound(page);
2216 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002217 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2218 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002219 // First, clear any pages that should no longer be loaded
2220 for (int i = 0; i < count; ++i) {
2221 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002222 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002223 if (layout.getPageChildCount() > 0) {
2224 layout.removeAllViewsOnPage();
2225 }
2226 mDirtyPageContent.set(i, true);
2227 }
2228 }
2229 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002230 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002231 if ((i != page) && immediateAndOnly) {
2232 continue;
2233 }
Michael Jurka0142d492010-08-25 17:46:15 -07002234 if (lowerPageBound <= i && i <= upperPageBound) {
2235 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002236 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002237 mDirtyPageContent.set(i, false);
2238 }
Winson Chung86f77532010-08-24 11:08:22 -07002239 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002240 }
2241 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002242 }
2243 }
2244
Winson Chunge3193b92010-09-10 11:44:42 -07002245 protected int getAssociatedLowerPageBound(int page) {
2246 return Math.max(0, page - 1);
2247 }
2248 protected int getAssociatedUpperPageBound(int page) {
2249 final int count = getChildCount();
2250 return Math.min(page + 1, count - 1);
2251 }
2252
Winson Chung86f77532010-08-24 11:08:22 -07002253 /**
2254 * This method is called ONLY to synchronize the number of pages that the paged view has.
2255 * To actually fill the pages with information, implement syncPageItems() below. It is
2256 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2257 * and therefore, individual page items do not need to be updated in this method.
2258 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002259 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002260
2261 /**
2262 * This method is called to synchronize the items that are on a particular page. If views on
2263 * the page can be reused, then they should be updated within this method.
2264 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002265 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002266
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002267 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002268 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002269 }
2270 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002271 invalidatePageData(currentPage, false);
2272 }
2273 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002274 if (!mIsDataReady) {
2275 return;
2276 }
2277
Michael Jurka0142d492010-08-25 17:46:15 -07002278 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002279 // Force all scrolling-related behavior to end
2280 mScroller.forceFinished(true);
2281 mNextPage = INVALID_PAGE;
2282
Michael Jurka0142d492010-08-25 17:46:15 -07002283 // Update all the pages
2284 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002285
Winson Chung5a808352011-06-27 19:08:49 -07002286 // We must force a measure after we've loaded the pages to update the content width and
2287 // to determine the full scroll width
2288 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2289 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2290
2291 // Set a new page as the current page if necessary
2292 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002293 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002294 }
2295
Michael Jurka0142d492010-08-25 17:46:15 -07002296 // Mark each of the pages as dirty
2297 final int count = getChildCount();
2298 mDirtyPageContent.clear();
2299 for (int i = 0; i < count; ++i) {
2300 mDirtyPageContent.add(true);
2301 }
2302
2303 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002304 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002305 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002306 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002307 }
Winson Chung007c6982011-06-14 13:27:53 -07002308
Adam Cohen7d30a372013-07-01 17:03:59 -07002309 // Animate the drag view back to the original position
2310 void animateDragViewToOriginalPosition() {
2311 if (mDragView != null) {
2312 AnimatorSet anim = new AnimatorSet();
2313 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2314 anim.playTogether(
2315 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002316 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2317 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2318 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002319 anim.addListener(new AnimatorListenerAdapter() {
2320 @Override
2321 public void onAnimationEnd(Animator animation) {
2322 onPostReorderingAnimationCompleted();
2323 }
2324 });
2325 anim.start();
2326 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002327 }
2328
Adam Cohen7d30a372013-07-01 17:03:59 -07002329 protected void onStartReordering() {
2330 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2331 mTouchState = TOUCH_STATE_REORDERING;
2332 mIsReordering = true;
2333
Adam Cohen7d30a372013-07-01 17:03:59 -07002334 // We must invalidate to trigger a redraw to update the layers such that the drag view
2335 // is always drawn on top
2336 invalidate();
2337 }
2338
2339 private void onPostReorderingAnimationCompleted() {
2340 // Trigger the callback when reordering has settled
2341 --mPostReorderingPreZoomInRemainingAnimationCount;
2342 if (mPostReorderingPreZoomInRunnable != null &&
2343 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2344 mPostReorderingPreZoomInRunnable.run();
2345 mPostReorderingPreZoomInRunnable = null;
2346 }
2347 }
2348
2349 protected void onEndReordering() {
2350 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002351 }
2352
Adam Cohenf358a4b2013-07-23 16:47:31 -07002353 public boolean startReordering(View v) {
2354 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002355 mTempVisiblePagesRange[0] = 0;
2356 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002357 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002358 mReorderingStarted = true;
2359
2360 // Check if we are within the reordering range
2361 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002362 dragViewIndex <= mTempVisiblePagesRange[1]) {
2363 // Find the drag view under the pointer
2364 mDragView = getChildAt(dragViewIndex);
2365 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2366 mDragViewBaselineLeft = mDragView.getLeft();
2367 disableFreeScroll(-1);
2368 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002369 return true;
2370 }
2371 return false;
2372 }
2373
2374 boolean isReordering(boolean testTouchState) {
2375 boolean state = mIsReordering;
2376 if (testTouchState) {
2377 state &= (mTouchState == TOUCH_STATE_REORDERING);
2378 }
2379 return state;
2380 }
2381 void endReordering() {
2382 // For simplicity, we call endReordering sometimes even if reordering was never started.
2383 // In that case, we don't want to do anything.
2384 if (!mReorderingStarted) return;
2385 mReorderingStarted = false;
2386
2387 // If we haven't flung-to-delete the current child, then we just animate the drag view
2388 // back into position
2389 final Runnable onCompleteRunnable = new Runnable() {
2390 @Override
2391 public void run() {
2392 onEndReordering();
2393 }
2394 };
2395 if (!mDeferringForDelete) {
2396 mPostReorderingPreZoomInRunnable = new Runnable() {
2397 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002398 onCompleteRunnable.run();
2399 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002400 };
2401 };
2402
2403 mPostReorderingPreZoomInRemainingAnimationCount =
2404 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2405 // Snap to the current page
2406 snapToPage(indexOfChild(mDragView), 0);
2407 // Animate the drag view back to the front position
2408 animateDragViewToOriginalPosition();
2409 } else {
2410 // Handled in post-delete-animation-callbacks
2411 }
2412 }
2413
Adam Cohen7d30a372013-07-01 17:03:59 -07002414 /*
2415 * Flinging to delete - IN PROGRESS
2416 */
2417 private PointF isFlingingToDelete() {
2418 ViewConfiguration config = ViewConfiguration.get(getContext());
2419 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2420
2421 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2422 // Do a quick dot product test to ensure that we are flinging upwards
2423 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2424 mVelocityTracker.getYVelocity());
2425 PointF upVec = new PointF(0f, -1f);
2426 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2427 (vel.length() * upVec.length()));
2428 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2429 return vel;
2430 }
2431 }
2432 return null;
2433 }
2434
2435 /**
2436 * Creates an animation from the current drag view along its current velocity vector.
2437 * For this animation, the alpha runs for a fixed duration and we update the position
2438 * progressively.
2439 */
2440 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2441 private View mDragView;
2442 private PointF mVelocity;
2443 private Rect mFrom;
2444 private long mPrevTime;
2445 private float mFriction;
2446
2447 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2448
2449 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2450 long startTime, float friction) {
2451 mDragView = dragView;
2452 mVelocity = vel;
2453 mFrom = from;
2454 mPrevTime = startTime;
2455 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2456 }
2457
2458 @Override
2459 public void onAnimationUpdate(ValueAnimator animation) {
2460 float t = ((Float) animation.getAnimatedValue()).floatValue();
2461 long curTime = AnimationUtils.currentAnimationTimeMillis();
2462
2463 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2464 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2465
2466 mDragView.setTranslationX(mFrom.left);
2467 mDragView.setTranslationY(mFrom.top);
2468 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2469
2470 mVelocity.x *= mFriction;
2471 mVelocity.y *= mFriction;
2472 mPrevTime = curTime;
2473 }
2474 };
2475
2476 private static final int ANIM_TAG_KEY = 100;
2477
2478 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2479 return new Runnable() {
2480 @Override
2481 public void run() {
2482 int dragViewIndex = indexOfChild(dragView);
2483
2484 // For each of the pages around the drag view, animate them from the previous
2485 // position to the new position in the layout (as a result of the drag view moving
2486 // in the layout)
2487 // NOTE: We can make an assumption here because we have side-bound pages that we
2488 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002489 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002490 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2491 boolean slideFromLeft = (isLastWidgetPage ||
2492 dragViewIndex > mTempVisiblePagesRange[0]);
2493
2494 // Setup the scroll to the correct page before we swap the views
2495 if (slideFromLeft) {
2496 snapToPageImmediately(dragViewIndex - 1);
2497 }
2498
2499 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2500 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2501 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2502 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2503 ArrayList<Animator> animations = new ArrayList<Animator>();
2504 for (int i = lowerIndex; i <= upperIndex; ++i) {
2505 View v = getChildAt(i);
2506 // dragViewIndex < pageUnderPointIndex, so after we remove the
2507 // drag view all subsequent views to pageUnderPointIndex will
2508 // shift down.
2509 int oldX = 0;
2510 int newX = 0;
2511 if (slideFromLeft) {
2512 if (i == 0) {
2513 // Simulate the page being offscreen with the page spacing
2514 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2515 - mPageSpacing;
2516 } else {
2517 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2518 }
2519 newX = getViewportOffsetX() + getChildOffset(i);
2520 } else {
2521 oldX = getChildOffset(i) - getChildOffset(i - 1);
2522 newX = 0;
2523 }
2524
2525 // Animate the view translation from its old position to its new
2526 // position
2527 AnimatorSet anim = (AnimatorSet) v.getTag();
2528 if (anim != null) {
2529 anim.cancel();
2530 }
2531
2532 // Note: Hacky, but we want to skip any optimizations to not draw completely
2533 // hidden views
2534 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2535 v.setTranslationX(oldX - newX);
2536 anim = new AnimatorSet();
2537 anim.playTogether(
2538 ObjectAnimator.ofFloat(v, "translationX", 0f),
2539 ObjectAnimator.ofFloat(v, "alpha", 1f));
2540 animations.add(anim);
2541 v.setTag(ANIM_TAG_KEY, anim);
2542 }
2543
2544 AnimatorSet slideAnimations = new AnimatorSet();
2545 slideAnimations.playTogether(animations);
2546 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2547 slideAnimations.addListener(new AnimatorListenerAdapter() {
2548 @Override
2549 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002550 mDeferringForDelete = false;
2551 onEndReordering();
2552 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002553 }
2554 });
2555 slideAnimations.start();
2556
2557 removeView(dragView);
2558 onRemoveView(dragView, true);
2559 }
2560 };
2561 }
2562
2563 public void onFlingToDelete(PointF vel) {
2564 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2565
2566 // NOTE: Because it takes time for the first frame of animation to actually be
2567 // called and we expect the animation to be a continuation of the fling, we have
2568 // to account for the time that has elapsed since the fling finished. And since
2569 // we don't have a startDelay, we will always get call to update when we call
2570 // start() (which we want to ignore).
2571 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2572 private int mCount = -1;
2573 private long mStartTime;
2574 private float mOffset;
2575 /* Anonymous inner class ctor */ {
2576 mStartTime = startTime;
2577 }
2578
2579 @Override
2580 public float getInterpolation(float t) {
2581 if (mCount < 0) {
2582 mCount++;
2583 } else if (mCount == 0) {
2584 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2585 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2586 mCount++;
2587 }
2588 return Math.min(1f, mOffset + t);
2589 }
2590 };
2591
2592 final Rect from = new Rect();
2593 final View dragView = mDragView;
2594 from.left = (int) dragView.getTranslationX();
2595 from.top = (int) dragView.getTranslationY();
2596 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2597 from, startTime, FLING_TO_DELETE_FRICTION);
2598
2599 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2600
2601 // Create and start the animation
2602 ValueAnimator mDropAnim = new ValueAnimator();
2603 mDropAnim.setInterpolator(tInterpolator);
2604 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2605 mDropAnim.setFloatValues(0f, 1f);
2606 mDropAnim.addUpdateListener(updateCb);
2607 mDropAnim.addListener(new AnimatorListenerAdapter() {
2608 public void onAnimationEnd(Animator animation) {
2609 onAnimationEndRunnable.run();
2610 }
2611 });
2612 mDropAnim.start();
2613 mDeferringForDelete = true;
2614 }
2615
2616 /* Drag to delete */
2617 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2618 if (mDeleteDropTarget != null) {
2619 mAltTmpRect.set(0, 0, 0, 0);
2620 View parent = (View) mDeleteDropTarget.getParent();
2621 if (parent != null) {
2622 parent.getGlobalVisibleRect(mAltTmpRect);
2623 }
2624 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2625 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2626 return mTmpRect.contains(x, y);
2627 }
2628 return false;
2629 }
2630
2631 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2632
2633 private void onDropToDelete() {
2634 final View dragView = mDragView;
2635
2636 final float toScale = 0f;
2637 final float toAlpha = 0f;
2638
2639 // Create and start the complex animation
2640 ArrayList<Animator> animations = new ArrayList<Animator>();
2641 AnimatorSet motionAnim = new AnimatorSet();
2642 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2643 motionAnim.playTogether(
2644 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2645 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2646 animations.add(motionAnim);
2647
2648 AnimatorSet alphaAnim = new AnimatorSet();
2649 alphaAnim.setInterpolator(new LinearInterpolator());
2650 alphaAnim.playTogether(
2651 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2652 animations.add(alphaAnim);
2653
2654 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2655
2656 AnimatorSet anim = new AnimatorSet();
2657 anim.playTogether(animations);
2658 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2659 anim.addListener(new AnimatorListenerAdapter() {
2660 public void onAnimationEnd(Animator animation) {
2661 onAnimationEndRunnable.run();
2662 }
2663 });
2664 anim.start();
2665
2666 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002667 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002668
2669 /* Accessibility */
2670 @Override
2671 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2672 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002673 info.setScrollable(getPageCount() > 1);
2674 if (getCurrentPage() < getPageCount() - 1) {
2675 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2676 }
2677 if (getCurrentPage() > 0) {
2678 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2679 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002680 }
2681
2682 @Override
2683 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2684 super.onInitializeAccessibilityEvent(event);
2685 event.setScrollable(true);
2686 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2687 event.setFromIndex(mCurrentPage);
2688 event.setToIndex(mCurrentPage);
2689 event.setItemCount(getChildCount());
2690 }
2691 }
2692
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002693 @Override
2694 public boolean performAccessibilityAction(int action, Bundle arguments) {
2695 if (super.performAccessibilityAction(action, arguments)) {
2696 return true;
2697 }
2698 switch (action) {
2699 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2700 if (getCurrentPage() < getPageCount() - 1) {
2701 scrollRight();
2702 return true;
2703 }
2704 } break;
2705 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2706 if (getCurrentPage() > 0) {
2707 scrollLeft();
2708 return true;
2709 }
2710 } break;
2711 }
2712 return false;
2713 }
2714
Adam Cohen0ffac432013-07-10 11:19:26 -07002715 protected String getCurrentPageDescription() {
2716 return String.format(getContext().getString(R.string.default_scroll_format),
2717 getNextPage() + 1, getChildCount());
2718 }
2719
Winson Chungd11265e2011-08-30 13:37:23 -07002720 @Override
2721 public boolean onHoverEvent(android.view.MotionEvent event) {
2722 return true;
2723 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002724}