blob: 763dfa1a908842f32b90618a020e278bc194fced [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
Winson Chung7819a562013-09-19 15:55:45 -0700340 ArrayList<PageIndicator.PageMarkerResources> markers =
341 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700342 for (int i = 0; i < getChildCount(); ++i) {
343 markers.add(getPageIndicatorMarker(i));
344 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700345
Winson Chungc58497e2013-09-03 17:48:37 -0700346 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700347 }
348 }
349
350 protected void onDetachedFromWindow() {
351 // Unhook the page indicator
352 mPageIndicator = null;
353 }
354
Adam Cohen7d30a372013-07-01 17:03:59 -0700355 void setDeleteDropTarget(View v) {
356 mDeleteDropTarget = v;
357 }
358
359 // Convenience methods to map points from self to parent and vice versa
360 float[] mapPointFromViewToParent(View v, float x, float y) {
361 mTmpPoint[0] = x;
362 mTmpPoint[1] = y;
363 v.getMatrix().mapPoints(mTmpPoint);
364 mTmpPoint[0] += v.getLeft();
365 mTmpPoint[1] += v.getTop();
366 return mTmpPoint;
367 }
368 float[] mapPointFromParentToView(View v, float x, float y) {
369 mTmpPoint[0] = x - v.getLeft();
370 mTmpPoint[1] = y - v.getTop();
371 v.getMatrix().invert(mTmpInvMatrix);
372 mTmpInvMatrix.mapPoints(mTmpPoint);
373 return mTmpPoint;
374 }
375
376 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700377 if (mDragView != null) {
378 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
379 (mDragViewBaselineLeft - mDragView.getLeft());
380 float y = mLastMotionY - mDownMotionY;
381 mDragView.setTranslationX(x);
382 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700383
Adam Cohenf358a4b2013-07-23 16:47:31 -0700384 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
385 + x + ", " + y);
386 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700387 }
388
389 public void setMinScale(float f) {
390 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700391 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700392 requestLayout();
393 }
394
395 @Override
396 public void setScaleX(float scaleX) {
397 super.setScaleX(scaleX);
398 if (isReordering(true)) {
399 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
400 mLastMotionX = p[0];
401 mLastMotionY = p[1];
402 updateDragViewTranslationDuringDrag();
403 }
404 }
405
406 // Convenience methods to get the actual width/height of the PagedView (since it is measured
407 // to be larger to account for the minimum possible scale)
408 int getViewportWidth() {
409 return mViewport.width();
410 }
411 int getViewportHeight() {
412 return mViewport.height();
413 }
414
415 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
416 // PagedView both horizontally and vertically
417 int getViewportOffsetX() {
418 return (getMeasuredWidth() - getViewportWidth()) / 2;
419 }
420
421 int getViewportOffsetY() {
422 return (getMeasuredHeight() - getViewportHeight()) / 2;
423 }
424
Adam Cohenedb40762013-07-18 16:45:45 -0700425 PageIndicator getPageIndicator() {
426 return mPageIndicator;
427 }
Winson Chung7819a562013-09-19 15:55:45 -0700428 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
429 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700430 }
Adam Cohenedb40762013-07-18 16:45:45 -0700431
Winson Chung86f77532010-08-24 11:08:22 -0700432 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
433 mPageSwitchListener = pageSwitchListener;
434 if (mPageSwitchListener != null) {
435 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700436 }
437 }
438
439 /**
Winson Chung52aee602013-01-30 12:01:02 -0800440 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
441 */
442 public boolean isLayoutRtl() {
443 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
444 }
445
446 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700447 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
448 * out pages.
449 */
450 protected void setDataIsReady() {
451 mIsDataReady = true;
452 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700453
Winson Chungf0ea4d32011-06-06 14:27:16 -0700454 protected boolean isDataReady() {
455 return mIsDataReady;
456 }
457
458 /**
Winson Chung86f77532010-08-24 11:08:22 -0700459 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700460 *
Winson Chung86f77532010-08-24 11:08:22 -0700461 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700462 */
Winson Chung86f77532010-08-24 11:08:22 -0700463 int getCurrentPage() {
464 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700465 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700466
Winson Chung360e63f2012-04-27 13:48:05 -0700467 int getNextPage() {
468 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
469 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700470
Winson Chung86f77532010-08-24 11:08:22 -0700471 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700472 return getChildCount();
473 }
474
Winson Chung86f77532010-08-24 11:08:22 -0700475 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700476 return getChildAt(index);
477 }
478
Adam Cohenae4f1552011-10-20 00:15:42 -0700479 protected int indexToPage(int index) {
480 return index;
481 }
482
Winson Chung321e9ee2010-08-09 13:37:56 -0700483 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800484 * Updates the scroll of the current page immediately to its final scroll position. We use this
485 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
486 * the previous tab page.
487 */
488 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700489 // If the current page is invalid, just reset the scroll position to zero
490 int newX = 0;
491 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700492 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700493 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800494 scrollTo(newX, 0);
495 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800496 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800497 }
498
499 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700500 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
501 * ends, {@link #resumeScrolling()} should be called, along with
502 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
503 */
504 void pauseScrolling() {
505 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700506 }
507
508 /**
509 * Enables scrolling again.
510 * @see #pauseScrolling()
511 */
512 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700513 }
514 /**
Winson Chung86f77532010-08-24 11:08:22 -0700515 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700516 */
Winson Chung86f77532010-08-24 11:08:22 -0700517 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800518 if (!mScroller.isFinished()) {
519 mScroller.abortAnimation();
520 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800521 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
522 // the default
523 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800524 return;
525 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700526
Adam Cohene61a9a22013-06-11 15:45:31 -0700527 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700528 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700529 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700530 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800531 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700532 }
533
Winson Chung8c87cd82013-07-23 16:20:10 -0700534 /**
535 * The restore page will be set in place of the current page at the next (likely first)
536 * layout.
537 */
538 void setRestorePage(int restorePage) {
539 mRestorePage = restorePage;
540 }
541
Michael Jurka0142d492010-08-25 17:46:15 -0700542 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700543 if (mPageSwitchListener != null) {
544 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700545 }
Winson Chungd2be3812013-07-16 11:11:32 -0700546
547 // Update the page indicator (when we aren't reordering)
548 if (mPageIndicator != null && !isReordering(false)) {
549 mPageIndicator.setActiveMarker(getNextPage());
550 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700551 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800552 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700553 if (!mIsPageMoving) {
554 mIsPageMoving = true;
555 onPageBeginMoving();
556 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700557 }
558
Michael Jurkace7e05f2011-02-01 22:02:35 -0800559 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700560 if (mIsPageMoving) {
561 mIsPageMoving = false;
562 onPageEndMoving();
563 }
Michael Jurka0142d492010-08-25 17:46:15 -0700564 }
565
Adam Cohen26976d92011-03-22 15:33:33 -0700566 protected boolean isPageMoving() {
567 return mIsPageMoving;
568 }
569
Michael Jurka0142d492010-08-25 17:46:15 -0700570 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700571 protected void onPageBeginMoving() {
572 }
573
574 // a method that subclasses can override to add behavior
575 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700576 }
577
Winson Chung321e9ee2010-08-09 13:37:56 -0700578 /**
Winson Chung86f77532010-08-24 11:08:22 -0700579 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700580 *
581 * @param l The listener used to respond to long clicks.
582 */
583 @Override
584 public void setOnLongClickListener(OnLongClickListener l) {
585 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700586 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700587 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700588 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700589 }
Adam Cohen1697b792013-09-17 19:08:21 -0700590 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700591 }
592
593 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800594 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700595 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800596 }
597
598 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700599 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700600 // In free scroll mode, we clamp the scrollX
601 if (mFreeScroll) {
602 x = Math.min(x, mFreeScrollMaxScrollX);
603 x = Math.max(x, mFreeScrollMinScrollX);
604 }
605
Adam Cohen0ffac432013-07-10 11:19:26 -0700606 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800607 mUnboundedScrollX = x;
608
Adam Cohen0ffac432013-07-10 11:19:26 -0700609 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
610 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
611 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800612 super.scrollTo(0, y);
613 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700614 if (isRtl) {
615 overScroll(x - mMaxScrollX);
616 } else {
617 overScroll(x);
618 }
Adam Cohen68d73932010-11-15 10:50:58 -0800619 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700620 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800621 super.scrollTo(mMaxScrollX, y);
622 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700623 if (isRtl) {
624 overScroll(x);
625 } else {
626 overScroll(x - mMaxScrollX);
627 }
Adam Cohen68d73932010-11-15 10:50:58 -0800628 }
629 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800630 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800631 super.scrollTo(x, y);
632 }
633
Michael Jurka0142d492010-08-25 17:46:15 -0700634 mTouchX = x;
635 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700636
637 // Update the last motion events when scrolling
638 if (isReordering(true)) {
639 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
640 mLastMotionX = p[0];
641 mLastMotionY = p[1];
642 updateDragViewTranslationDuringDrag();
643 }
Michael Jurka0142d492010-08-25 17:46:15 -0700644 }
645
646 // we moved this functionality to a helper function so SmoothPagedView can reuse it
647 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700648 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700649 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700650 if (getScrollX() != mScroller.getCurrX()
651 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700652 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700653 float scaleX = mFreeScroll ? getScaleX() : 1f;
654 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
655 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700656 }
Michael Jurka0142d492010-08-25 17:46:15 -0700657 invalidate();
658 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700659 } else if (mNextPage != INVALID_PAGE) {
660 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700661 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700662 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700663
Winson Chung9c0565f2013-07-19 13:49:06 -0700664 // Load the associated pages if necessary
665 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
666 loadAssociatedPages(mCurrentPage);
667 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
668 }
669
Adam Cohen73aa9752010-11-24 16:26:58 -0800670 // We don't want to trigger a page end moving unless the page has settled
671 // and the user has stopped scrolling
672 if (mTouchState == TOUCH_STATE_REST) {
673 pageEndMoving();
674 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700675
Adam Cohen7d30a372013-07-01 17:03:59 -0700676 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700677 // Notify the user when the page changes
678 AccessibilityManager accessibilityManager = (AccessibilityManager)
679 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
680 if (accessibilityManager.isEnabled()) {
681 AccessibilityEvent ev =
682 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
683 ev.getText().add(getCurrentPageDescription());
684 sendAccessibilityEventUnchecked(ev);
685 }
Michael Jurka0142d492010-08-25 17:46:15 -0700686 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700687 }
Michael Jurka0142d492010-08-25 17:46:15 -0700688 return false;
689 }
690
691 @Override
692 public void computeScroll() {
693 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700694 }
695
Adam Cohen7d30a372013-07-01 17:03:59 -0700696 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
697 return mTopAlignPageWhenShrinkingForBouncer;
698 }
699
Adam Cohen96d30a12013-07-16 18:13:21 -0700700 public static class LayoutParams extends ViewGroup.LayoutParams {
701 public boolean isFullScreenPage = false;
702
703 /**
704 * {@inheritDoc}
705 */
706 public LayoutParams(int width, int height) {
707 super(width, height);
708 }
709
710 public LayoutParams(ViewGroup.LayoutParams source) {
711 super(source);
712 }
713 }
714
715 protected LayoutParams generateDefaultLayoutParams() {
716 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
717 }
718
Adam Cohenedb40762013-07-18 16:45:45 -0700719 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700720 LayoutParams lp = generateDefaultLayoutParams();
721 lp.isFullScreenPage = true;
722 super.addView(page, 0, lp);
723 }
724
Winson Chung321e9ee2010-08-09 13:37:56 -0700725 @Override
726 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700727 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700728 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
729 return;
730 }
731
Adam Cohen7d30a372013-07-01 17:03:59 -0700732 // We measure the dimensions of the PagedView to be larger than the pages so that when we
733 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700734 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
735 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
736 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700737 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700738 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
739 // viewport, we can be at most one and a half screens offset once we scale down
740 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700741 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Winson Chungc58497e2013-09-03 17:48:37 -0700742 int parentWidthSize, parentHeightSize;
743 int scaledWidthSize, scaledHeightSize;
744 if (mUseMinScale) {
745 parentWidthSize = (int) (1.5f * maxSize);
746 parentHeightSize = maxSize;
747 scaledWidthSize = (int) (parentWidthSize / mMinScale);
748 scaledHeightSize = (int) (parentHeightSize / mMinScale);
749 } else {
750 scaledWidthSize = widthSize;
751 scaledHeightSize = heightSize;
752 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700753 mViewport.set(0, 0, widthSize, heightSize);
754
755 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
756 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
757 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700758 }
759
Winson Chung8aad6102012-05-11 16:27:49 -0700760 // Return early if we aren't given a proper dimension
761 if (widthSize <= 0 || heightSize <= 0) {
762 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
763 return;
764 }
765
Adam Lesinski6b879f02010-11-04 16:15:23 -0700766 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
767 * of the All apps view on XLarge displays to not take up more space then it needs. Width
768 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
769 * each page to have the same width.
770 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700771 final int verticalPadding = getPaddingTop() + getPaddingBottom();
772 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700773
774 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700775 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700776 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700777 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
778 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
779 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
780 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700781 final int childCount = getChildCount();
782 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700783 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700784 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700785 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
786
787 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700788 int childHeightMode;
789 int childWidth;
790 int childHeight;
791
792 if (!lp.isFullScreenPage) {
793 if (lp.width == LayoutParams.WRAP_CONTENT) {
794 childWidthMode = MeasureSpec.AT_MOST;
795 } else {
796 childWidthMode = MeasureSpec.EXACTLY;
797 }
798
799 if (lp.height == LayoutParams.WRAP_CONTENT) {
800 childHeightMode = MeasureSpec.AT_MOST;
801 } else {
802 childHeightMode = MeasureSpec.EXACTLY;
803 }
804
805 childWidth = widthSize - horizontalPadding;
John Spurlock77e1f472013-09-11 10:09:51 -0400806 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
Adam Cohen96d30a12013-07-16 18:13:21 -0700807
Michael Jurka5f1c5092010-09-03 14:15:02 -0700808 } else {
809 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700810 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700811
Winson Chungc58497e2013-09-03 17:48:37 -0700812 if (mUseMinScale) {
813 childWidth = getViewportWidth();
814 childHeight = getViewportHeight();
815 } else {
816 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
817 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
818 }
Michael Jurka5f1c5092010-09-03 14:15:02 -0700819 }
820
821 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700822 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
823 final int childHeightMeasureSpec =
824 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700825 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700826 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700827 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700828
Winson Chunga128a7b2012-04-30 15:23:15 -0700829 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700830 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700831 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700832 // The gap between pages in the PagedView should be equal to the gap from the page
833 // to the edge of the screen (so it is not visible in the current screen). To
834 // account for unequal padding on each side of the paged view, we take the maximum
835 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700836 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700837 int spacing = Math.max(offset, widthSize - offset -
838 getChildAt(0).getMeasuredWidth());
839 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700840 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700841 }
842 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700843 }
844
Adam Cohen60b07122011-11-14 17:26:06 -0800845 public void setPageSpacing(int pageSpacing) {
846 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700847 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800848 }
849
Winson Chung321e9ee2010-08-09 13:37:56 -0700850 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700851 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700852 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700853 return;
854 }
855
Winson Chung785d2eb2011-04-14 16:08:02 -0700856 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700857 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700858
Adam Cohenedb40762013-07-18 16:45:45 -0700859 int screenWidth = getViewportWidth();
860
Adam Cohen7d30a372013-07-01 17:03:59 -0700861 int offsetX = getViewportOffsetX();
862 int offsetY = getViewportOffsetY();
863
864 // Update the viewport offsets
865 mViewport.offset(offsetX, offsetY);
866
Adam Cohen0ffac432013-07-10 11:19:26 -0700867 final boolean isRtl = isLayoutRtl();
868
869 final int startIndex = isRtl ? childCount - 1 : 0;
870 final int endIndex = isRtl ? -1 : childCount;
871 final int delta = isRtl ? -1 : 1;
872
Adam Cohen7d30a372013-07-01 17:03:59 -0700873 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700874 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
875
876 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
877 mPageScrolls = new int[getChildCount()];
878 }
879
Adam Cohen0ffac432013-07-10 11:19:26 -0700880 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700881 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700882 LayoutParams lp = (LayoutParams) child.getLayoutParams();
883 int childTop;
Adam Cohen96d30a12013-07-16 18:13:21 -0700884 if (lp.isFullScreenPage) {
885 childTop = offsetY;
886 } else {
John Spurlock77e1f472013-09-11 10:09:51 -0400887 childTop = offsetY + getPaddingTop() + mInsets.top;
Adam Cohen96d30a12013-07-16 18:13:21 -0700888 if (mCenterPagesVertically) {
John Spurlock77e1f472013-09-11 10:09:51 -0400889 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
Adam Cohen96d30a12013-07-16 18:13:21 -0700890 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700891 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700892
Winson Chung321e9ee2010-08-09 13:37:56 -0700893 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700894 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700895 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800896
Winson Chung785d2eb2011-04-14 16:08:02 -0700897 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700898 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800899 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700900
901 // We assume the left and right padding are equal, and hence center the pages
902 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700903 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700904 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
905
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700906 if (i != endIndex - delta) {
907 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
908 childLeft += childWidth + nextScrollOffset;
909 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700910 }
911 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700912
913 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
914 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800915 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700916 setHorizontalScrollBarEnabled(true);
917 mFirstLayout = false;
918 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700919
920 if (childCount > 0) {
921 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700922 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700923 } else {
924 mMaxScrollX = 0;
925 }
926
927 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
928 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700929 if (mRestorePage > -1) {
930 setCurrentPage(mRestorePage);
931 mRestorePage = -1;
932 } else {
933 setCurrentPage(getNextPage());
934 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700935 }
936 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700937
938 if (isReordering(true)) {
939 updateDragViewTranslationDuringDrag();
940 }
Winson Chunge3193b92010-09-10 11:44:42 -0700941 }
942
Adam Cohenf34bab52010-09-30 14:11:56 -0700943 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700944 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
945
946 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700947 for (int i = 0; i < getChildCount(); i++) {
948 View child = getChildAt(i);
949 if (child != null) {
950 float scrollProgress = getScrollProgress(screenCenter, child, i);
951 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800952 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700953 }
954 }
955 invalidate();
956 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700957 }
958
Winson Chungc58497e2013-09-03 17:48:37 -0700959 protected void enablePagedViewAnimations() {
960 mAllowPagedViewAnimations = true;
961
962 }
963 protected void disablePagedViewAnimations() {
964 mAllowPagedViewAnimations = false;
965 }
966
Winson Chunge3193b92010-09-10 11:44:42 -0700967 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700968 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700969 // Update the page indicator, we don't update the page indicator as we
970 // add/remove pages
971 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700972 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -0700973 mPageIndicator.addMarker(pageIndex,
974 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -0700975 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700976 }
977
Adam Cohen2591f6a2011-10-25 14:36:40 -0700978 // This ensures that when children are added, they get the correct transforms / alphas
979 // in accordance with any scroll effects.
980 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700981 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700982
Adam Cohen2591f6a2011-10-25 14:36:40 -0700983 invalidate();
984 }
985
Michael Jurka8b805b12012-04-18 14:23:14 -0700986 @Override
987 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700988 mForceScreenScrolled = true;
989 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700990 }
991
Winson Chungd2be3812013-07-16 11:11:32 -0700992 private void removeMarkerForView(int index) {
993 // Update the page indicator, we don't update the page indicator as we
994 // add/remove pages
995 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -0700996 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -0700997 }
998 }
999
1000 @Override
1001 public void removeView(View v) {
1002 // XXX: We should find a better way to hook into this before the view
1003 // gets removed form its parent...
1004 removeMarkerForView(indexOfChild(v));
1005 super.removeView(v);
1006 }
1007 @Override
1008 public void removeViewInLayout(View v) {
1009 // XXX: We should find a better way to hook into this before the view
1010 // gets removed form its parent...
1011 removeMarkerForView(indexOfChild(v));
1012 super.removeViewInLayout(v);
1013 }
1014 @Override
1015 public void removeViewAt(int index) {
1016 // XXX: We should find a better way to hook into this before the view
1017 // gets removed form its parent...
1018 removeViewAt(index);
1019 super.removeViewAt(index);
1020 }
1021 @Override
1022 public void removeAllViewsInLayout() {
1023 // Update the page indicator, we don't update the page indicator as we
1024 // add/remove pages
1025 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001026 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001027 }
1028
1029 super.removeAllViewsInLayout();
1030 }
1031
Adam Cohen73894962011-10-31 13:17:17 -07001032 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001033 if (index < 0 || index > getChildCount() - 1) return 0;
1034
Adam Cohen0ffac432013-07-10 11:19:26 -07001035 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -07001036
Adam Cohenf698c6e2013-07-17 18:44:25 -07001037 if (isRtl) index = getChildCount() - index - 1;
1038 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001039
Adam Cohenf698c6e2013-07-17 18:44:25 -07001040 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001041 }
1042
Adam Cohenf358a4b2013-07-23 16:47:31 -07001043 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001044 range[0] = 0;
1045 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001046 }
1047
Michael Jurkadde558b2011-11-09 22:09:06 -08001048 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001049 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001050 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001051
Michael Jurkac4fb9172010-09-02 17:19:20 -07001052 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001053 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001054 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001055 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001056
Winson Chungc9ca2982013-07-19 12:07:38 -07001057 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1058 View currPage = getPageAt(leftScreen);
1059
1060 // Check if the right edge of the page is in the viewport
1061 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001062 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001063 if (mTmpIntPoint[0] < 0) {
1064 break;
1065 }
1066 }
1067 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1068 View currPage = getPageAt(rightScreen);
1069
1070 // Check if the left edge of the page is in the viewport
1071 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001072 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001073 if (mTmpIntPoint[0] >= viewportWidth) {
1074 break;
1075 }
1076 }
1077 range[0] = Math.max(0, leftScreen);
1078 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001079 } else {
1080 range[0] = -1;
1081 range[1] = -1;
1082 }
1083 }
1084
Michael Jurka920d7f42012-05-14 16:29:55 -07001085 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001086 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001087 }
1088
Michael Jurkadde558b2011-11-09 22:09:06 -08001089 @Override
1090 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001091 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001092 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1093 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001094 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001095
1096 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001097 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1098 // set it for the next frame
1099 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001100 screenScrolled(screenCenter);
1101 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001102 }
1103
1104 // Find out which screens are visible; as an optimization we only call draw on them
1105 final int pageCount = getChildCount();
1106 if (pageCount > 0) {
1107 getVisiblePages(mTempVisiblePagesRange);
1108 final int leftScreen = mTempVisiblePagesRange[0];
1109 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001110 if (leftScreen != -1 && rightScreen != -1) {
1111 final long drawingTime = getDrawingTime();
1112 // Clip to the bounds
1113 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001114 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1115 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001116
Adam Cohen7d30a372013-07-01 17:03:59 -07001117 // Draw all the children, leaving the drag view for last
1118 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001119 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001120 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001121 if (mForceDrawAllChildrenNextFrame ||
1122 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001123 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001124 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001125 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001126 // Draw the drag view on top (if there is one)
1127 if (mDragView != null) {
1128 drawChild(canvas, mDragView, drawingTime);
1129 }
1130
Michael Jurka5e368ff2012-05-14 23:13:15 -07001131 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001132 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001133 }
Michael Jurka0142d492010-08-25 17:46:15 -07001134 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001135 }
1136
1137 @Override
1138 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001139 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001140 if (page != mCurrentPage || !mScroller.isFinished()) {
1141 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001142 return true;
1143 }
1144 return false;
1145 }
1146
1147 @Override
1148 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001149 int focusablePage;
1150 if (mNextPage != INVALID_PAGE) {
1151 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001152 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001153 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001154 }
Winson Chung86f77532010-08-24 11:08:22 -07001155 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001156 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001157 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001158 }
1159 return false;
1160 }
1161
1162 @Override
1163 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001164 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001165 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001166 if (getCurrentPage() > 0) {
1167 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001168 return true;
1169 }
1170 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001171 if (getCurrentPage() < getPageCount() - 1) {
1172 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001173 return true;
1174 }
1175 }
1176 return super.dispatchUnhandledMove(focused, direction);
1177 }
1178
1179 @Override
1180 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001181 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001182 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001183 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001184 }
1185 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001186 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001187 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001188 }
1189 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001190 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001191 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001192 }
1193 }
1194 }
1195
1196 /**
1197 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001198 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001199 *
Winson Chung86f77532010-08-24 11:08:22 -07001200 * This happens when live folders requery, and if they're off page, they
1201 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001202 */
1203 @Override
1204 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001205 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001206 View v = focused;
1207 while (true) {
1208 if (v == current) {
1209 super.focusableViewAvailable(focused);
1210 return;
1211 }
1212 if (v == this) {
1213 return;
1214 }
1215 ViewParent parent = v.getParent();
1216 if (parent instanceof View) {
1217 v = (View)v.getParent();
1218 } else {
1219 return;
1220 }
1221 }
1222 }
1223
1224 /**
1225 * {@inheritDoc}
1226 */
1227 @Override
1228 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1229 if (disallowIntercept) {
1230 // We need to make sure to cancel our long press if
1231 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001232 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001233 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001234 }
1235 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1236 }
1237
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001238 /**
1239 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1240 */
1241 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001242 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001243 if (isLayoutRtl()) {
1244 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001245 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001246 }
Adam Cohenedb40762013-07-18 16:45:45 -07001247 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001248 }
1249
1250 /**
1251 * Return true if a tap at (x, y) should trigger a flip to the next page.
1252 */
1253 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001254 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001255 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001256 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001257 }
1258 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001259 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001260 }
Winson Chung52aee602013-01-30 12:01:02 -08001261
Adam Cohen7d30a372013-07-01 17:03:59 -07001262 /** Returns whether x and y originated within the buffered viewport */
1263 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1264 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1265 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1266 return mTmpRect.contains(x, y);
1267 }
1268
Winson Chung321e9ee2010-08-09 13:37:56 -07001269 @Override
1270 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001271 if (DISABLE_TOUCH_INTERACTION) {
1272 return false;
1273 }
1274
Winson Chung321e9ee2010-08-09 13:37:56 -07001275 /*
1276 * This method JUST determines whether we want to intercept the motion.
1277 * If we return true, onTouchEvent will be called and we do the actual
1278 * scrolling there.
1279 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001280 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001281
Winson Chung45e1d6e2010-11-09 17:19:49 -08001282 // Skip touch handling if there are no pages to swipe
1283 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1284
Winson Chung321e9ee2010-08-09 13:37:56 -07001285 /*
1286 * Shortcut the most recurring case: the user is in the dragging
1287 * state and he is moving his finger. We want to intercept this
1288 * motion.
1289 */
1290 final int action = ev.getAction();
1291 if ((action == MotionEvent.ACTION_MOVE) &&
1292 (mTouchState == TOUCH_STATE_SCROLLING)) {
1293 return true;
1294 }
1295
Winson Chung321e9ee2010-08-09 13:37:56 -07001296 switch (action & MotionEvent.ACTION_MASK) {
1297 case MotionEvent.ACTION_MOVE: {
1298 /*
1299 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1300 * whether the user has moved far enough from his original down touch.
1301 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001302 if (mActivePointerId != INVALID_POINTER) {
1303 determineScrollingStart(ev);
1304 break;
1305 }
1306 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1307 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1308 // i.e. fall through to the next case (don't break)
1309 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1310 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001311 }
1312
1313 case MotionEvent.ACTION_DOWN: {
1314 final float x = ev.getX();
1315 final float y = ev.getY();
1316 // Remember location of down touch
1317 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001318 mDownMotionY = y;
1319 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001320 mLastMotionX = x;
1321 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001322 float[] p = mapPointFromViewToParent(this, x, y);
1323 mParentDownMotionX = p[0];
1324 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001325 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001326 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001327 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001328
Winson Chung321e9ee2010-08-09 13:37:56 -07001329 /*
1330 * If being flinged and user touches the screen, initiate drag;
1331 * otherwise don't. mScroller.isFinished should be false when
1332 * being flinged.
1333 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001334 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001335 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1336 if (finishedScrolling) {
1337 mTouchState = TOUCH_STATE_REST;
1338 mScroller.abortAnimation();
1339 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001340 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1341 mTouchState = TOUCH_STATE_SCROLLING;
1342 } else {
1343 mTouchState = TOUCH_STATE_REST;
1344 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001345 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001346
Winson Chung86f77532010-08-24 11:08:22 -07001347 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001348 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001349 if (!DISABLE_TOUCH_SIDE_PAGES) {
1350 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1351 if (getChildCount() > 0) {
1352 if (hitsPreviousPage(x, y)) {
1353 mTouchState = TOUCH_STATE_PREV_PAGE;
1354 } else if (hitsNextPage(x, y)) {
1355 mTouchState = TOUCH_STATE_NEXT_PAGE;
1356 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001357 }
1358 }
1359 }
1360 break;
1361 }
1362
Winson Chung321e9ee2010-08-09 13:37:56 -07001363 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001364 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001365 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001366 break;
1367
1368 case MotionEvent.ACTION_POINTER_UP:
1369 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001370 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001371 break;
1372 }
1373
1374 /*
1375 * The only time we want to intercept motion events is if we are in the
1376 * drag mode.
1377 */
1378 return mTouchState != TOUCH_STATE_REST;
1379 }
1380
Adam Cohenf8d28232011-02-01 21:47:00 -08001381 protected void determineScrollingStart(MotionEvent ev) {
1382 determineScrollingStart(ev, 1.0f);
1383 }
1384
Winson Chung321e9ee2010-08-09 13:37:56 -07001385 /*
1386 * Determines if we should change the touch state to start scrolling after the
1387 * user moves their touch point too far.
1388 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001389 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001390 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001391 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001392 if (pointerIndex == -1) return;
1393
1394 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001395 final float x = ev.getX(pointerIndex);
1396 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001397 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1398
Winson Chung321e9ee2010-08-09 13:37:56 -07001399 final int xDiff = (int) Math.abs(x - mLastMotionX);
1400 final int yDiff = (int) Math.abs(y - mLastMotionY);
1401
Adam Cohenf8d28232011-02-01 21:47:00 -08001402 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001403 boolean xPaged = xDiff > mPagingTouchSlop;
1404 boolean xMoved = xDiff > touchSlop;
1405 boolean yMoved = yDiff > touchSlop;
1406
Adam Cohenf8d28232011-02-01 21:47:00 -08001407 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001408 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001409 // Scroll if the user moved far enough along the X axis
1410 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001411 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001412 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001413 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001414 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001415 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1416 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001417 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001418 }
1419 }
1420
Adam Cohen7d30a372013-07-01 17:03:59 -07001421 protected float getMaxScrollProgress() {
1422 return 1.0f;
1423 }
1424
Adam Cohenf8d28232011-02-01 21:47:00 -08001425 protected void cancelCurrentPageLongPress() {
1426 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001427 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001428 // Try canceling the long press. It could also have been scheduled
1429 // by a distant descendant, so use the mAllowLongPress flag to block
1430 // everything
1431 final View currentPage = getPageAt(mCurrentPage);
1432 if (currentPage != null) {
1433 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001434 }
1435 }
1436 }
1437
Adam Cohen7d30a372013-07-01 17:03:59 -07001438 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1439 final int halfScreenSize = getViewportWidth() / 2;
1440
1441 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1442 screenCenter = Math.max(halfScreenSize, screenCenter);
1443
1444 return getScrollProgress(screenCenter, v, page);
1445 }
1446
Adam Cohenb5ba0972011-09-07 18:02:31 -07001447 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001448 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001449
Adam Cohen96d30a12013-07-16 18:13:21 -07001450 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001451 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001452
1453 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001454 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1455 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001456 return scrollProgress;
1457 }
1458
Adam Cohenedb40762013-07-18 16:45:45 -07001459 public int getScrollForPage(int index) {
1460 if (mPageScrolls == null || index >= mPageScrolls.length) {
1461 return 0;
1462 } else {
1463 return mPageScrolls[index];
1464 }
1465 }
1466
Adam Cohene0f66b52010-11-23 15:06:07 -08001467 // This curve determines how the effect of scrolling over the limits of the page dimishes
1468 // as the user pulls further and further from the bounds
1469 private float overScrollInfluenceCurve(float f) {
1470 f -= 1.0f;
1471 return f * f * f + 1.0f;
1472 }
1473
Adam Cohenb5ba0972011-09-07 18:02:31 -07001474 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001475 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001476
1477 // We want to reach the max over scroll effect when the user has
1478 // over scrolled half the size of the screen
1479 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1480
1481 if (f == 0) return;
1482
1483 // Clamp this factor, f, to -1 < f < 1
1484 if (Math.abs(f) >= 1) {
1485 f /= Math.abs(f);
1486 }
1487
1488 int overScrollAmount = (int) Math.round(f * screenSize);
1489 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001490 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001491 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001492 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001493 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001494 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001495 }
1496 invalidate();
1497 }
1498
1499 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001500 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001501
1502 float f = (amount / screenSize);
1503
1504 if (f == 0) return;
1505 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1506
Adam Cohen7bfc9792011-01-28 13:52:37 -08001507 // Clamp this factor, f, to -1 < f < 1
1508 if (Math.abs(f) >= 1) {
1509 f /= Math.abs(f);
1510 }
1511
Adam Cohene0f66b52010-11-23 15:06:07 -08001512 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001513 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001514 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001515 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001516 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001517 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001518 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001519 }
1520 invalidate();
1521 }
1522
Adam Cohenb5ba0972011-09-07 18:02:31 -07001523 protected void overScroll(float amount) {
1524 dampedOverScroll(amount);
1525 }
1526
Michael Jurkac5b262c2011-01-12 20:24:50 -08001527 protected float maxOverScroll() {
1528 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001529 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001530 float f = 1.0f;
1531 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1532 return OVERSCROLL_DAMP_FACTOR * f;
1533 }
1534
Adam Cohenf358a4b2013-07-23 16:47:31 -07001535 protected void enableFreeScroll() {
1536 setEnableFreeScroll(true, -1);
1537 }
1538
1539 protected void disableFreeScroll(int snapPage) {
1540 setEnableFreeScroll(false, snapPage);
1541 }
1542
1543 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1544 mFreeScroll = freeScroll;
1545
1546 if (snapPage == -1) {
1547 snapPage = getPageNearestToCenterOfScreen();
1548 }
1549
1550 getOverviewModePages(mTempVisiblePagesRange);
1551 if (!mFreeScroll) {
1552 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001553 } else {
1554 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1555 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1556
Adam Cohenf358a4b2013-07-23 16:47:31 -07001557 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1558 setCurrentPage(mTempVisiblePagesRange[0]);
1559 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1560 setCurrentPage(mTempVisiblePagesRange[1]);
1561 }
1562 }
1563
1564 setEnableOverscroll(!freeScroll);
1565 }
1566
1567 private void setEnableOverscroll(boolean enable) {
1568 mAllowOverScroll = enable;
1569 }
1570
1571 int getNearestHoverOverPageIndex() {
1572 if (mDragView != null) {
1573 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1574 + mDragView.getTranslationX());
1575 getOverviewModePages(mTempVisiblePagesRange);
1576 int minDistance = Integer.MAX_VALUE;
1577 int minIndex = indexOfChild(mDragView);
1578 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1579 View page = getPageAt(i);
1580 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1581 int d = Math.abs(dragX - pageX);
1582 if (d < minDistance) {
1583 minIndex = i;
1584 minDistance = d;
1585 }
1586 }
1587 return minIndex;
1588 }
1589 return -1;
1590 }
1591
Winson Chung321e9ee2010-08-09 13:37:56 -07001592 @Override
1593 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001594 if (DISABLE_TOUCH_INTERACTION) {
1595 return false;
1596 }
1597
Adam Cohen1697b792013-09-17 19:08:21 -07001598 super.onTouchEvent(ev);
1599
Winson Chung45e1d6e2010-11-09 17:19:49 -08001600 // Skip touch handling if there are no pages to swipe
1601 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1602
Michael Jurkab8f06722010-10-10 15:58:46 -07001603 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001604
1605 final int action = ev.getAction();
1606
1607 switch (action & MotionEvent.ACTION_MASK) {
1608 case MotionEvent.ACTION_DOWN:
1609 /*
1610 * If being flinged and user touches, stop the fling. isFinished
1611 * will be false if being flinged.
1612 */
1613 if (!mScroller.isFinished()) {
1614 mScroller.abortAnimation();
1615 }
1616
1617 // Remember where the motion event started
1618 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001619 mDownMotionY = mLastMotionY = ev.getY();
1620 mDownScrollX = getScrollX();
1621 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1622 mParentDownMotionX = p[0];
1623 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001624 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001625 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001626 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001627
Michael Jurka0142d492010-08-25 17:46:15 -07001628 if (mTouchState == TOUCH_STATE_SCROLLING) {
1629 pageBeginMoving();
1630 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001631 break;
1632
1633 case MotionEvent.ACTION_MOVE:
1634 if (mTouchState == TOUCH_STATE_SCROLLING) {
1635 // Scroll to follow the motion event
1636 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001637
1638 if (pointerIndex == -1) return true;
1639
Winson Chung321e9ee2010-08-09 13:37:56 -07001640 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001641 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001642
Adam Cohenaefd4e12011-02-14 16:39:38 -08001643 mTotalMotionX += Math.abs(deltaX);
1644
Winson Chungc0844aa2011-02-02 15:25:58 -08001645 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1646 // keep the remainder because we are actually testing if we've moved from the last
1647 // scrolled position (which is discrete).
1648 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001649 mTouchX += deltaX;
1650 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1651 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001652 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001653 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001654 } else {
1655 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001656 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001657 mLastMotionX = x;
1658 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001659 } else {
1660 awakenScrollBars();
1661 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001662 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1663 // Update the last motion position
1664 mLastMotionX = ev.getX();
1665 mLastMotionY = ev.getY();
1666
1667 // Update the parent down so that our zoom animations take this new movement into
1668 // account
1669 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1670 mParentDownMotionX = pt[0];
1671 mParentDownMotionY = pt[1];
1672 updateDragViewTranslationDuringDrag();
1673
1674 // Find the closest page to the touch point
1675 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001676
1677 // Change the drag view if we are hovering over the drop target
1678 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1679 (int) mParentDownMotionX, (int) mParentDownMotionY);
1680 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1681
Adam Cohen7d30a372013-07-01 17:03:59 -07001682 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1683 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1684 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1685 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1686
Adam Cohenf358a4b2013-07-23 16:47:31 -07001687 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1688 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1689 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001690 mTempVisiblePagesRange[0] = 0;
1691 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001692 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001693 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1694 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1695 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1696 mSidePageHoverIndex = pageUnderPointIndex;
1697 mSidePageHoverRunnable = new Runnable() {
1698 @Override
1699 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001700 // Setup the scroll to the correct page before we swap the views
1701 snapToPage(pageUnderPointIndex);
1702
1703 // For each of the pages between the paged view and the drag view,
1704 // animate them from the previous position to the new position in
1705 // the layout (as a result of the drag view moving in the layout)
1706 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1707 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1708 dragViewIndex + 1 : pageUnderPointIndex;
1709 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1710 dragViewIndex - 1 : pageUnderPointIndex;
1711 for (int i = lowerIndex; i <= upperIndex; ++i) {
1712 View v = getChildAt(i);
1713 // dragViewIndex < pageUnderPointIndex, so after we remove the
1714 // drag view all subsequent views to pageUnderPointIndex will
1715 // shift down.
1716 int oldX = getViewportOffsetX() + getChildOffset(i);
1717 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1718
1719 // Animate the view translation from its old position to its new
1720 // position
1721 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1722 if (anim != null) {
1723 anim.cancel();
1724 }
1725
1726 v.setTranslationX(oldX - newX);
1727 anim = new AnimatorSet();
1728 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1729 anim.playTogether(
1730 ObjectAnimator.ofFloat(v, "translationX", 0f));
1731 anim.start();
1732 v.setTag(anim);
1733 }
1734
1735 removeView(mDragView);
1736 onRemoveView(mDragView, false);
1737 addView(mDragView, pageUnderPointIndex);
1738 onAddView(mDragView, pageUnderPointIndex);
1739 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001740 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001741 }
1742 };
1743 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1744 }
1745 } else {
1746 removeCallbacks(mSidePageHoverRunnable);
1747 mSidePageHoverIndex = -1;
1748 }
Adam Cohen564976a2010-10-13 18:52:07 -07001749 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001750 determineScrollingStart(ev);
1751 }
1752 break;
1753
1754 case MotionEvent.ACTION_UP:
1755 if (mTouchState == TOUCH_STATE_SCROLLING) {
1756 final int activePointerId = mActivePointerId;
1757 final int pointerIndex = ev.findPointerIndex(activePointerId);
1758 final float x = ev.getX(pointerIndex);
1759 final VelocityTracker velocityTracker = mVelocityTracker;
1760 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1761 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001762 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001763 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001764 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1765 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001766
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001767 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1768
Adam Cohen00481b32011-11-18 12:03:48 -08001769 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001770 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001771
Adam Cohenf358a4b2013-07-23 16:47:31 -07001772 if (!mFreeScroll) {
1773 // In the case that the page is moved far to one direction and then is flung
1774 // in the opposite direction, we use a threshold to determine whether we should
1775 // just return to the starting page, or if we should skip one further.
1776 boolean returnToOriginalPage = false;
1777 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1778 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1779 returnToOriginalPage = true;
1780 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001781
Adam Cohenf358a4b2013-07-23 16:47:31 -07001782 int finalPage;
1783 // We give flings precedence over large moves, which is why we short-circuit our
1784 // test for a large move if a fling has been registered. That is, a large
1785 // move to the left and fling to the right will register as a fling to the right.
1786 final boolean isRtl = isLayoutRtl();
1787 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1788 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1789 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1790 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1791 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1792 snapToPageWithVelocity(finalPage, velocityX);
1793 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1794 (isFling && isVelocityXLeft)) &&
1795 mCurrentPage < getChildCount() - 1) {
1796 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1797 snapToPageWithVelocity(finalPage, velocityX);
1798 } else {
1799 snapToDestination();
1800 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1801 // at this point we have not moved beyond the touch slop
1802 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1803 // we can just page
1804 int nextPage = Math.max(0, mCurrentPage - 1);
1805 if (nextPage != mCurrentPage) {
1806 snapToPage(nextPage);
1807 } else {
1808 snapToDestination();
1809 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001810 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001811 if (!mScroller.isFinished()) {
1812 mScroller.abortAnimation();
1813 }
1814
1815 float scaleX = getScaleX();
1816 int vX = (int) (-velocityX * scaleX);
1817 int initialScrollX = (int) (getScrollX() * scaleX);
1818
1819 mScroller.fling(initialScrollX,
1820 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1821 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001822 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001823 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001824 // at this point we have not moved beyond the touch slop
1825 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1826 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001827 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1828 if (nextPage != mCurrentPage) {
1829 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001830 } else {
1831 snapToDestination();
1832 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001833 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1834 // Update the last motion position
1835 mLastMotionX = ev.getX();
1836 mLastMotionY = ev.getY();
1837
1838 // Update the parent down so that our zoom animations take this new movement into
1839 // account
1840 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1841 mParentDownMotionX = pt[0];
1842 mParentDownMotionY = pt[1];
1843 updateDragViewTranslationDuringDrag();
1844 boolean handledFling = false;
1845 if (!DISABLE_FLING_TO_DELETE) {
1846 // Check the velocity and see if we are flinging-to-delete
1847 PointF flingToDeleteVector = isFlingingToDelete();
1848 if (flingToDeleteVector != null) {
1849 onFlingToDelete(flingToDeleteVector);
1850 handledFling = true;
1851 }
1852 }
1853 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1854 (int) mParentDownMotionY)) {
1855 onDropToDelete();
1856 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001857 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001858 if (!mCancelTap) {
1859 onUnhandledTap(ev);
1860 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001861 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001862
1863 // Remove the callback to wait for the side page hover timeout
1864 removeCallbacks(mSidePageHoverRunnable);
1865 // End any intermediate reordering states
1866 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001867 break;
1868
1869 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001870 if (mTouchState == TOUCH_STATE_SCROLLING) {
1871 snapToDestination();
1872 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001873 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001874 break;
1875
1876 case MotionEvent.ACTION_POINTER_UP:
1877 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001878 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001879 break;
1880 }
1881
1882 return true;
1883 }
1884
Adam Cohen7d30a372013-07-01 17:03:59 -07001885 public void onFlingToDelete(View v) {}
1886 public void onRemoveView(View v, boolean deletePermanently) {}
1887 public void onRemoveViewAnimationCompleted() {}
1888 public void onAddView(View v, int index) {}
1889
1890 private void resetTouchState() {
1891 releaseVelocityTracker();
1892 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001893 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001894 mTouchState = TOUCH_STATE_REST;
1895 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001896 }
1897
Adam Cohen1697b792013-09-17 19:08:21 -07001898 protected void onUnhandledTap(MotionEvent ev) {
1899 ((Launcher) getContext()).onClick(this);
1900 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001901
Winson Chung185d7162011-02-28 13:47:29 -08001902 @Override
1903 public boolean onGenericMotionEvent(MotionEvent event) {
1904 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1905 switch (event.getAction()) {
1906 case MotionEvent.ACTION_SCROLL: {
1907 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1908 final float vscroll;
1909 final float hscroll;
1910 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1911 vscroll = 0;
1912 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1913 } else {
1914 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1915 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1916 }
1917 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001918 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1919 : (hscroll > 0 || vscroll > 0);
1920 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001921 scrollRight();
1922 } else {
1923 scrollLeft();
1924 }
1925 return true;
1926 }
1927 }
1928 }
1929 }
1930 return super.onGenericMotionEvent(event);
1931 }
1932
Michael Jurkab8f06722010-10-10 15:58:46 -07001933 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1934 if (mVelocityTracker == null) {
1935 mVelocityTracker = VelocityTracker.obtain();
1936 }
1937 mVelocityTracker.addMovement(ev);
1938 }
1939
1940 private void releaseVelocityTracker() {
1941 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001942 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07001943 mVelocityTracker.recycle();
1944 mVelocityTracker = null;
1945 }
1946 }
1947
Winson Chung321e9ee2010-08-09 13:37:56 -07001948 private void onSecondaryPointerUp(MotionEvent ev) {
1949 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1950 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1951 final int pointerId = ev.getPointerId(pointerIndex);
1952 if (pointerId == mActivePointerId) {
1953 // This was our active pointer going up. Choose a new
1954 // active pointer and adjust accordingly.
1955 // TODO: Make this decision more intelligent.
1956 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1957 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1958 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001959 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001960 mActivePointerId = ev.getPointerId(newPointerIndex);
1961 if (mVelocityTracker != null) {
1962 mVelocityTracker.clear();
1963 }
1964 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001965 }
1966
Winson Chung321e9ee2010-08-09 13:37:56 -07001967 @Override
1968 public void requestChildFocus(View child, View focused) {
1969 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001970 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001971 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001972 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001973 }
1974 }
1975
Winson Chung1908d072011-02-24 18:09:44 -08001976 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001977 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001978 }
1979
Adam Cohen7d30a372013-07-01 17:03:59 -07001980 int getPageNearestToPoint(float x) {
1981 int index = 0;
1982 for (int i = 0; i < getChildCount(); ++i) {
1983 if (x < getChildAt(i).getRight() - getScrollX()) {
1984 return index;
1985 } else {
1986 index++;
1987 }
1988 }
1989 return Math.min(index, getChildCount() - 1);
1990 }
1991
Adam Cohend19d3ca2010-09-15 14:43:42 -07001992 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001993 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001994 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001995 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001996 final int childCount = getChildCount();
1997 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001998 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001999 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002000 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002001 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002002 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2003 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2004 minDistanceFromScreenCenter = distanceFromScreenCenter;
2005 minDistanceFromScreenCenterIndex = i;
2006 }
2007 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002008 return minDistanceFromScreenCenterIndex;
2009 }
2010
2011 protected void snapToDestination() {
2012 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002013 }
2014
Adam Cohene0f66b52010-11-23 15:06:07 -08002015 private static class ScrollInterpolator implements Interpolator {
2016 public ScrollInterpolator() {
2017 }
2018
2019 public float getInterpolation(float t) {
2020 t -= 1.0f;
2021 return t*t*t*t*t + 1;
2022 }
2023 }
2024
2025 // We want the duration of the page snap animation to be influenced by the distance that
2026 // the screen has to travel, however, we don't want this duration to be effected in a
2027 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2028 // of travel has on the overall snap duration.
2029 float distanceInfluenceForSnapDuration(float f) {
2030 f -= 0.5f; // center the values about 0.
2031 f *= 0.3f * Math.PI / 2.0f;
2032 return (float) Math.sin(f);
2033 }
2034
Michael Jurka0142d492010-08-25 17:46:15 -07002035 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002036 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002037 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002038
Adam Cohenedb40762013-07-18 16:45:45 -07002039 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002040 int delta = newX - mUnboundedScrollX;
2041 int duration = 0;
2042
Adam Cohen265b9a62011-12-07 14:37:18 -08002043 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002044 // If the velocity is low enough, then treat this more as an automatic page advance
2045 // as opposed to an apparent physical response to flinging
2046 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2047 return;
2048 }
2049
2050 // Here we compute a "distance" that will be used in the computation of the overall
2051 // snap duration. This is a function of the actual distance that needs to be traveled;
2052 // we keep this value close to half screen size in order to reduce the variance in snap
2053 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002054 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002055 float distance = halfScreenSize + halfScreenSize *
2056 distanceInfluenceForSnapDuration(distanceRatio);
2057
2058 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002059 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002060
2061 // we want the page's snap velocity to approximately match the velocity at which the
2062 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002063 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2064 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002065
2066 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002067 }
2068
2069 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002070 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002071 }
2072
Adam Cohen7d30a372013-07-01 17:03:59 -07002073 protected void snapToPageImmediately(int whichPage) {
2074 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2075 }
2076
Michael Jurka0142d492010-08-25 17:46:15 -07002077 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002078 snapToPage(whichPage, duration, false);
2079 }
2080
2081 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002082 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002083
Adam Cohenedb40762013-07-18 16:45:45 -07002084 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002085 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002086 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002087 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002088 }
2089
2090 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002091 snapToPage(whichPage, delta, duration, false);
2092 }
Michael Jurka0142d492010-08-25 17:46:15 -07002093
Adam Cohen7d30a372013-07-01 17:03:59 -07002094 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2095 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002096 View focusedChild = getFocusedChild();
2097 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002098 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002099 focusedChild.clearFocus();
2100 }
2101
2102 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002103 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002104 if (immediate) {
2105 duration = 0;
2106 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002107 duration = Math.abs(delta);
2108 }
2109
Adam Cohenf358a4b2013-07-23 16:47:31 -07002110 if (!mScroller.isFinished()) {
2111 mScroller.abortAnimation();
2112 }
Adam Cohen68d73932010-11-15 10:50:58 -08002113 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002114
Michael Jurka0142d492010-08-25 17:46:15 -07002115 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002116
2117 // Trigger a compute() to finish switching pages if necessary
2118 if (immediate) {
2119 computeScroll();
2120 }
2121
Winson Chung9c0565f2013-07-19 13:49:06 -07002122 // Defer loading associated pages until the scroll settles
2123 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2124
Adam Cohen7d30a372013-07-01 17:03:59 -07002125 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002126 invalidate();
2127 }
2128
Winson Chung321e9ee2010-08-09 13:37:56 -07002129 public void scrollLeft() {
2130 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002131 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002132 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002133 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002134 }
2135 }
2136
2137 public void scrollRight() {
2138 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002139 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002140 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002141 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002142 }
2143 }
2144
Winson Chung86f77532010-08-24 11:08:22 -07002145 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002146 int result = -1;
2147 if (v != null) {
2148 ViewParent vp = v.getParent();
2149 int count = getChildCount();
2150 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002151 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002152 return i;
2153 }
2154 }
2155 }
2156 return result;
2157 }
2158
2159 /**
2160 * @return True is long presses are still allowed for the current touch
2161 */
2162 public boolean allowLongPress() {
2163 return mAllowLongPress;
2164 }
2165
Adam Cohendbdff6b2013-09-18 19:09:15 -07002166 @Override
2167 public boolean performLongClick() {
2168 mCancelTap = true;
2169 return super.performLongClick();
2170 }
2171
Michael Jurka0142d492010-08-25 17:46:15 -07002172 /**
2173 * Set true to allow long-press events to be triggered, usually checked by
2174 * {@link Launcher} to accept or block dpad-initiated long-presses.
2175 */
2176 public void setAllowLongPress(boolean allowLongPress) {
2177 mAllowLongPress = allowLongPress;
2178 }
2179
Winson Chung321e9ee2010-08-09 13:37:56 -07002180 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002181 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002182
2183 SavedState(Parcelable superState) {
2184 super(superState);
2185 }
2186
2187 private SavedState(Parcel in) {
2188 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002189 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002190 }
2191
2192 @Override
2193 public void writeToParcel(Parcel out, int flags) {
2194 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002195 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002196 }
2197
2198 public static final Parcelable.Creator<SavedState> CREATOR =
2199 new Parcelable.Creator<SavedState>() {
2200 public SavedState createFromParcel(Parcel in) {
2201 return new SavedState(in);
2202 }
2203
2204 public SavedState[] newArray(int size) {
2205 return new SavedState[size];
2206 }
2207 };
2208 }
2209
Winson Chungf314b0e2011-08-16 11:54:27 -07002210 protected void loadAssociatedPages(int page) {
2211 loadAssociatedPages(page, false);
2212 }
2213 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002214 if (mContentIsRefreshable) {
2215 final int count = getChildCount();
2216 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002217 int lowerPageBound = getAssociatedLowerPageBound(page);
2218 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002219 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2220 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002221 // First, clear any pages that should no longer be loaded
2222 for (int i = 0; i < count; ++i) {
2223 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002224 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002225 if (layout.getPageChildCount() > 0) {
2226 layout.removeAllViewsOnPage();
2227 }
2228 mDirtyPageContent.set(i, true);
2229 }
2230 }
2231 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002232 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002233 if ((i != page) && immediateAndOnly) {
2234 continue;
2235 }
Michael Jurka0142d492010-08-25 17:46:15 -07002236 if (lowerPageBound <= i && i <= upperPageBound) {
2237 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002238 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002239 mDirtyPageContent.set(i, false);
2240 }
Winson Chung86f77532010-08-24 11:08:22 -07002241 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002242 }
2243 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002244 }
2245 }
2246
Winson Chunge3193b92010-09-10 11:44:42 -07002247 protected int getAssociatedLowerPageBound(int page) {
2248 return Math.max(0, page - 1);
2249 }
2250 protected int getAssociatedUpperPageBound(int page) {
2251 final int count = getChildCount();
2252 return Math.min(page + 1, count - 1);
2253 }
2254
Winson Chung86f77532010-08-24 11:08:22 -07002255 /**
2256 * This method is called ONLY to synchronize the number of pages that the paged view has.
2257 * To actually fill the pages with information, implement syncPageItems() below. It is
2258 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2259 * and therefore, individual page items do not need to be updated in this method.
2260 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002261 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002262
2263 /**
2264 * This method is called to synchronize the items that are on a particular page. If views on
2265 * the page can be reused, then they should be updated within this method.
2266 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002267 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002268
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002269 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002270 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002271 }
2272 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002273 invalidatePageData(currentPage, false);
2274 }
2275 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002276 if (!mIsDataReady) {
2277 return;
2278 }
2279
Michael Jurka0142d492010-08-25 17:46:15 -07002280 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002281 // Force all scrolling-related behavior to end
2282 mScroller.forceFinished(true);
2283 mNextPage = INVALID_PAGE;
2284
Michael Jurka0142d492010-08-25 17:46:15 -07002285 // Update all the pages
2286 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002287
Winson Chung5a808352011-06-27 19:08:49 -07002288 // We must force a measure after we've loaded the pages to update the content width and
2289 // to determine the full scroll width
2290 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2291 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2292
2293 // Set a new page as the current page if necessary
2294 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002295 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002296 }
2297
Michael Jurka0142d492010-08-25 17:46:15 -07002298 // Mark each of the pages as dirty
2299 final int count = getChildCount();
2300 mDirtyPageContent.clear();
2301 for (int i = 0; i < count; ++i) {
2302 mDirtyPageContent.add(true);
2303 }
2304
2305 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002306 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002307 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002308 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002309 }
Winson Chung007c6982011-06-14 13:27:53 -07002310
Adam Cohen7d30a372013-07-01 17:03:59 -07002311 // Animate the drag view back to the original position
2312 void animateDragViewToOriginalPosition() {
2313 if (mDragView != null) {
2314 AnimatorSet anim = new AnimatorSet();
2315 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2316 anim.playTogether(
2317 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002318 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2319 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2320 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002321 anim.addListener(new AnimatorListenerAdapter() {
2322 @Override
2323 public void onAnimationEnd(Animator animation) {
2324 onPostReorderingAnimationCompleted();
2325 }
2326 });
2327 anim.start();
2328 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002329 }
2330
Adam Cohen7d30a372013-07-01 17:03:59 -07002331 protected void onStartReordering() {
2332 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2333 mTouchState = TOUCH_STATE_REORDERING;
2334 mIsReordering = true;
2335
Adam Cohen7d30a372013-07-01 17:03:59 -07002336 // We must invalidate to trigger a redraw to update the layers such that the drag view
2337 // is always drawn on top
2338 invalidate();
2339 }
2340
2341 private void onPostReorderingAnimationCompleted() {
2342 // Trigger the callback when reordering has settled
2343 --mPostReorderingPreZoomInRemainingAnimationCount;
2344 if (mPostReorderingPreZoomInRunnable != null &&
2345 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2346 mPostReorderingPreZoomInRunnable.run();
2347 mPostReorderingPreZoomInRunnable = null;
2348 }
2349 }
2350
2351 protected void onEndReordering() {
2352 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002353 }
2354
Adam Cohenf358a4b2013-07-23 16:47:31 -07002355 public boolean startReordering(View v) {
2356 int dragViewIndex = indexOfChild(v);//getPageNearestToCenterOfScreen();
Adam Cohen7d30a372013-07-01 17:03:59 -07002357 mTempVisiblePagesRange[0] = 0;
2358 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002359 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002360 mReorderingStarted = true;
2361
2362 // Check if we are within the reordering range
2363 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002364 dragViewIndex <= mTempVisiblePagesRange[1]) {
2365 // Find the drag view under the pointer
2366 mDragView = getChildAt(dragViewIndex);
2367 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2368 mDragViewBaselineLeft = mDragView.getLeft();
2369 disableFreeScroll(-1);
2370 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002371 return true;
2372 }
2373 return false;
2374 }
2375
2376 boolean isReordering(boolean testTouchState) {
2377 boolean state = mIsReordering;
2378 if (testTouchState) {
2379 state &= (mTouchState == TOUCH_STATE_REORDERING);
2380 }
2381 return state;
2382 }
2383 void endReordering() {
2384 // For simplicity, we call endReordering sometimes even if reordering was never started.
2385 // In that case, we don't want to do anything.
2386 if (!mReorderingStarted) return;
2387 mReorderingStarted = false;
2388
2389 // If we haven't flung-to-delete the current child, then we just animate the drag view
2390 // back into position
2391 final Runnable onCompleteRunnable = new Runnable() {
2392 @Override
2393 public void run() {
2394 onEndReordering();
2395 }
2396 };
2397 if (!mDeferringForDelete) {
2398 mPostReorderingPreZoomInRunnable = new Runnable() {
2399 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002400 onCompleteRunnable.run();
2401 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002402 };
2403 };
2404
2405 mPostReorderingPreZoomInRemainingAnimationCount =
2406 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2407 // Snap to the current page
2408 snapToPage(indexOfChild(mDragView), 0);
2409 // Animate the drag view back to the front position
2410 animateDragViewToOriginalPosition();
2411 } else {
2412 // Handled in post-delete-animation-callbacks
2413 }
2414 }
2415
Adam Cohen7d30a372013-07-01 17:03:59 -07002416 /*
2417 * Flinging to delete - IN PROGRESS
2418 */
2419 private PointF isFlingingToDelete() {
2420 ViewConfiguration config = ViewConfiguration.get(getContext());
2421 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2422
2423 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2424 // Do a quick dot product test to ensure that we are flinging upwards
2425 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2426 mVelocityTracker.getYVelocity());
2427 PointF upVec = new PointF(0f, -1f);
2428 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2429 (vel.length() * upVec.length()));
2430 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2431 return vel;
2432 }
2433 }
2434 return null;
2435 }
2436
2437 /**
2438 * Creates an animation from the current drag view along its current velocity vector.
2439 * For this animation, the alpha runs for a fixed duration and we update the position
2440 * progressively.
2441 */
2442 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2443 private View mDragView;
2444 private PointF mVelocity;
2445 private Rect mFrom;
2446 private long mPrevTime;
2447 private float mFriction;
2448
2449 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2450
2451 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2452 long startTime, float friction) {
2453 mDragView = dragView;
2454 mVelocity = vel;
2455 mFrom = from;
2456 mPrevTime = startTime;
2457 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2458 }
2459
2460 @Override
2461 public void onAnimationUpdate(ValueAnimator animation) {
2462 float t = ((Float) animation.getAnimatedValue()).floatValue();
2463 long curTime = AnimationUtils.currentAnimationTimeMillis();
2464
2465 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2466 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2467
2468 mDragView.setTranslationX(mFrom.left);
2469 mDragView.setTranslationY(mFrom.top);
2470 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2471
2472 mVelocity.x *= mFriction;
2473 mVelocity.y *= mFriction;
2474 mPrevTime = curTime;
2475 }
2476 };
2477
2478 private static final int ANIM_TAG_KEY = 100;
2479
2480 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2481 return new Runnable() {
2482 @Override
2483 public void run() {
2484 int dragViewIndex = indexOfChild(dragView);
2485
2486 // For each of the pages around the drag view, animate them from the previous
2487 // position to the new position in the layout (as a result of the drag view moving
2488 // in the layout)
2489 // NOTE: We can make an assumption here because we have side-bound pages that we
2490 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002491 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002492 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2493 boolean slideFromLeft = (isLastWidgetPage ||
2494 dragViewIndex > mTempVisiblePagesRange[0]);
2495
2496 // Setup the scroll to the correct page before we swap the views
2497 if (slideFromLeft) {
2498 snapToPageImmediately(dragViewIndex - 1);
2499 }
2500
2501 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2502 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2503 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2504 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2505 ArrayList<Animator> animations = new ArrayList<Animator>();
2506 for (int i = lowerIndex; i <= upperIndex; ++i) {
2507 View v = getChildAt(i);
2508 // dragViewIndex < pageUnderPointIndex, so after we remove the
2509 // drag view all subsequent views to pageUnderPointIndex will
2510 // shift down.
2511 int oldX = 0;
2512 int newX = 0;
2513 if (slideFromLeft) {
2514 if (i == 0) {
2515 // Simulate the page being offscreen with the page spacing
2516 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2517 - mPageSpacing;
2518 } else {
2519 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2520 }
2521 newX = getViewportOffsetX() + getChildOffset(i);
2522 } else {
2523 oldX = getChildOffset(i) - getChildOffset(i - 1);
2524 newX = 0;
2525 }
2526
2527 // Animate the view translation from its old position to its new
2528 // position
2529 AnimatorSet anim = (AnimatorSet) v.getTag();
2530 if (anim != null) {
2531 anim.cancel();
2532 }
2533
2534 // Note: Hacky, but we want to skip any optimizations to not draw completely
2535 // hidden views
2536 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2537 v.setTranslationX(oldX - newX);
2538 anim = new AnimatorSet();
2539 anim.playTogether(
2540 ObjectAnimator.ofFloat(v, "translationX", 0f),
2541 ObjectAnimator.ofFloat(v, "alpha", 1f));
2542 animations.add(anim);
2543 v.setTag(ANIM_TAG_KEY, anim);
2544 }
2545
2546 AnimatorSet slideAnimations = new AnimatorSet();
2547 slideAnimations.playTogether(animations);
2548 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2549 slideAnimations.addListener(new AnimatorListenerAdapter() {
2550 @Override
2551 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002552 mDeferringForDelete = false;
2553 onEndReordering();
2554 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002555 }
2556 });
2557 slideAnimations.start();
2558
2559 removeView(dragView);
2560 onRemoveView(dragView, true);
2561 }
2562 };
2563 }
2564
2565 public void onFlingToDelete(PointF vel) {
2566 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2567
2568 // NOTE: Because it takes time for the first frame of animation to actually be
2569 // called and we expect the animation to be a continuation of the fling, we have
2570 // to account for the time that has elapsed since the fling finished. And since
2571 // we don't have a startDelay, we will always get call to update when we call
2572 // start() (which we want to ignore).
2573 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2574 private int mCount = -1;
2575 private long mStartTime;
2576 private float mOffset;
2577 /* Anonymous inner class ctor */ {
2578 mStartTime = startTime;
2579 }
2580
2581 @Override
2582 public float getInterpolation(float t) {
2583 if (mCount < 0) {
2584 mCount++;
2585 } else if (mCount == 0) {
2586 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2587 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2588 mCount++;
2589 }
2590 return Math.min(1f, mOffset + t);
2591 }
2592 };
2593
2594 final Rect from = new Rect();
2595 final View dragView = mDragView;
2596 from.left = (int) dragView.getTranslationX();
2597 from.top = (int) dragView.getTranslationY();
2598 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2599 from, startTime, FLING_TO_DELETE_FRICTION);
2600
2601 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2602
2603 // Create and start the animation
2604 ValueAnimator mDropAnim = new ValueAnimator();
2605 mDropAnim.setInterpolator(tInterpolator);
2606 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2607 mDropAnim.setFloatValues(0f, 1f);
2608 mDropAnim.addUpdateListener(updateCb);
2609 mDropAnim.addListener(new AnimatorListenerAdapter() {
2610 public void onAnimationEnd(Animator animation) {
2611 onAnimationEndRunnable.run();
2612 }
2613 });
2614 mDropAnim.start();
2615 mDeferringForDelete = true;
2616 }
2617
2618 /* Drag to delete */
2619 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2620 if (mDeleteDropTarget != null) {
2621 mAltTmpRect.set(0, 0, 0, 0);
2622 View parent = (View) mDeleteDropTarget.getParent();
2623 if (parent != null) {
2624 parent.getGlobalVisibleRect(mAltTmpRect);
2625 }
2626 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2627 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2628 return mTmpRect.contains(x, y);
2629 }
2630 return false;
2631 }
2632
2633 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2634
2635 private void onDropToDelete() {
2636 final View dragView = mDragView;
2637
2638 final float toScale = 0f;
2639 final float toAlpha = 0f;
2640
2641 // Create and start the complex animation
2642 ArrayList<Animator> animations = new ArrayList<Animator>();
2643 AnimatorSet motionAnim = new AnimatorSet();
2644 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2645 motionAnim.playTogether(
2646 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2647 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2648 animations.add(motionAnim);
2649
2650 AnimatorSet alphaAnim = new AnimatorSet();
2651 alphaAnim.setInterpolator(new LinearInterpolator());
2652 alphaAnim.playTogether(
2653 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2654 animations.add(alphaAnim);
2655
2656 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2657
2658 AnimatorSet anim = new AnimatorSet();
2659 anim.playTogether(animations);
2660 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2661 anim.addListener(new AnimatorListenerAdapter() {
2662 public void onAnimationEnd(Animator animation) {
2663 onAnimationEndRunnable.run();
2664 }
2665 });
2666 anim.start();
2667
2668 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002669 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002670
2671 /* Accessibility */
2672 @Override
2673 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2674 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002675 info.setScrollable(getPageCount() > 1);
2676 if (getCurrentPage() < getPageCount() - 1) {
2677 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2678 }
2679 if (getCurrentPage() > 0) {
2680 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2681 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002682 }
2683
2684 @Override
2685 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2686 super.onInitializeAccessibilityEvent(event);
2687 event.setScrollable(true);
2688 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2689 event.setFromIndex(mCurrentPage);
2690 event.setToIndex(mCurrentPage);
2691 event.setItemCount(getChildCount());
2692 }
2693 }
2694
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002695 @Override
2696 public boolean performAccessibilityAction(int action, Bundle arguments) {
2697 if (super.performAccessibilityAction(action, arguments)) {
2698 return true;
2699 }
2700 switch (action) {
2701 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2702 if (getCurrentPage() < getPageCount() - 1) {
2703 scrollRight();
2704 return true;
2705 }
2706 } break;
2707 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2708 if (getCurrentPage() > 0) {
2709 scrollLeft();
2710 return true;
2711 }
2712 } break;
2713 }
2714 return false;
2715 }
2716
Adam Cohen0ffac432013-07-10 11:19:26 -07002717 protected String getCurrentPageDescription() {
2718 return String.format(getContext().getString(R.string.default_scroll_format),
2719 getNextPage() + 1, getChildCount());
2720 }
2721
Winson Chungd11265e2011-08-30 13:37:23 -07002722 @Override
2723 public boolean onHoverEvent(android.view.MotionEvent event) {
2724 return true;
2725 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002726}