blob: e982985f12c27bd50995674c7740ec780258f531 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
Adam Cohen53805212013-10-01 10:39:23 -070035import android.support.v4.view.accessibility.AccessibilityEventCompat;
Winson Chung321e9ee2010-08-09 13:37:56 -070036import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070047import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070048import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070049import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070050import android.view.animation.AnimationUtils;
51import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080052import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070053import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070054import android.widget.Scroller;
55
Winson Chung6a0f57d2011-06-29 20:10:49 -070056import java.util.ArrayList;
57
Winson Chungc58497e2013-09-03 17:48:37 -070058interface Page {
59 public int getPageChildCount();
60 public View getChildOnPageAt(int i);
61 public void removeAllViewsOnPage();
62 public void removeViewOnPageAt(int i);
63 public int indexOfChildOnPage(View v);
64}
65
Winson Chung321e9ee2010-08-09 13:37:56 -070066/**
67 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070068 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070069 */
Michael Jurka8b805b12012-04-18 14:23:14 -070070public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070071 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070072 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070073 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070074
Winson Chung86f77532010-08-24 11:08:22 -070075 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070076 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070077
Adam Cohen7d30a372013-07-01 17:03:59 -070078 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070079 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070080 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070081
Adam Cohenb5ba0972011-09-07 18:02:31 -070082 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070083 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080084
Adam Cohenb64cb5a2011-02-15 13:53:42 -080085 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080086 // The page is moved more than halfway, automatically move to the next page on touch up.
87 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080088
Adam Cohen265b9a62011-12-07 14:37:18 -080089 // The following constants need to be scaled based on density. The scaled versions will be
90 // assigned to the corresponding member variables below.
91 private static final int FLING_THRESHOLD_VELOCITY = 500;
92 private static final int MIN_SNAP_VELOCITY = 1500;
93 private static final int MIN_FLING_VELOCITY = 250;
94
Adam Cohen7d30a372013-07-01 17:03:59 -070095 // We are disabling touch interaction of the widget region for factory ROM.
96 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070097 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070098 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070099
Adam Cohen21cd0022013-10-09 18:57:02 -0700100 public static final int INVALID_RESTORE_PAGE = -1001;
101
Adam Cohenf358a4b2013-07-23 16:47:31 -0700102 private boolean mFreeScroll = false;
103 private int mFreeScrollMinScrollX = -1;
104 private int mFreeScrollMaxScrollX = -1;
105
Winson Chung8aad6102012-05-11 16:27:49 -0700106 static final int AUTOMATIC_PAGE_SPACING = -1;
107
Adam Cohen265b9a62011-12-07 14:37:18 -0800108 protected int mFlingThresholdVelocity;
109 protected int mMinFlingVelocity;
110 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700111
Adam Cohenb5ba0972011-09-07 18:02:31 -0700112 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700113 protected float mSmoothingTime;
114 protected float mTouchX;
115
116 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700117 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700118
119 protected int mCurrentPage;
Adam Cohen21cd0022013-10-09 18:57:02 -0700120 protected int mRestorePage = INVALID_RESTORE_PAGE;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700121 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700122
Michael Jurka0142d492010-08-25 17:46:15 -0700123 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800124 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700125 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700126 private VelocityTracker mVelocityTracker;
127
Adam Cohen7d30a372013-07-01 17:03:59 -0700128 private float mParentDownMotionX;
129 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700130 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700131 private float mDownMotionY;
132 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700133 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800134 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800135 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800136 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800137 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700138 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700139
Adam Cohendbdff6b2013-09-18 19:09:15 -0700140 private boolean mCancelTap;
141
Adam Cohenedb40762013-07-18 16:45:45 -0700142 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700143
Michael Jurka0142d492010-08-25 17:46:15 -0700144 protected final static int TOUCH_STATE_REST = 0;
145 protected final static int TOUCH_STATE_SCROLLING = 1;
146 protected final static int TOUCH_STATE_PREV_PAGE = 2;
147 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700148 protected final static int TOUCH_STATE_REORDERING = 4;
149
Adam Cohene45440e2010-10-14 18:33:38 -0700150 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700151
Michael Jurka0142d492010-08-25 17:46:15 -0700152 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700153 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700154
Michael Jurka0142d492010-08-25 17:46:15 -0700155 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700156
Michael Jurka7426c422010-11-11 15:23:47 -0800157 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700158 private int mPagingTouchSlop;
159 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700160 protected int mPageSpacing;
161 protected int mPageLayoutPaddingTop;
162 protected int mPageLayoutPaddingBottom;
163 protected int mPageLayoutPaddingLeft;
164 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700165 protected int mPageLayoutWidthGap;
166 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700167 protected int mCellCountX = 0;
168 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700169 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800170 protected boolean mAllowOverScroll = true;
171 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800172 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700173 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700174
Michael Jurka8b805b12012-04-18 14:23:14 -0700175 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800176 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
177 // the screens from continuing to translate beyond the normal bounds.
178 protected int mOverScrollX;
179
Michael Jurka5f1c5092010-09-03 14:15:02 -0700180 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700181
Michael Jurka5f1c5092010-09-03 14:15:02 -0700182 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700183
Winson Chung86f77532010-08-24 11:08:22 -0700184 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700185
Michael Jurkae326f182011-11-21 14:05:46 -0800186 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700187
Michael Jurka0142d492010-08-25 17:46:15 -0700188 // If true, syncPages and syncPageItems will be called to refresh pages
189 protected boolean mContentIsRefreshable = true;
190
191 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700192 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700193
194 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
195 // to switch to a new page
196 protected boolean mUsePagingTouchSlop = true;
197
Michael Jurka8b805b12012-04-18 14:23:14 -0700198 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700199 // (SmoothPagedView does this)
200 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700201 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700202
Patrick Dubroy1262e362010-10-06 15:49:50 -0700203 protected boolean mIsPageMoving = false;
204
Winson Chungf0ea4d32011-06-06 14:27:16 -0700205 // All syncs and layout passes are deferred until data is ready.
206 protected boolean mIsDataReady = false;
207
Adam Cohen7d30a372013-07-01 17:03:59 -0700208 protected boolean mAllowLongPress = true;
209
Winson Chungd2be3812013-07-16 11:11:32 -0700210 // Page Indicator
211 private int mPageIndicatorViewId;
212 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700213 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700214
Adam Cohen7d30a372013-07-01 17:03:59 -0700215 // The viewport whether the pages are to be contained (the actual view may be larger than the
216 // viewport)
217 private Rect mViewport = new Rect();
218
219 // Reordering
220 // We use the min scale to determine how much to expand the actually PagedView measured
221 // dimensions such that when we are zoomed out, the view is not clipped
222 private int REORDERING_DROP_REPOSITION_DURATION = 200;
223 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
224 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700225 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700226 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700227 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700228 protected View mDragView;
229 protected AnimatorSet mZoomInOutAnim;
230 private Runnable mSidePageHoverRunnable;
231 private int mSidePageHoverIndex = -1;
232 // This variable's scope is only for the duration of startReordering() and endReordering()
233 private boolean mReorderingStarted = false;
234 // This variable's scope is for the duration of startReordering() and after the zoomIn()
235 // animation after endReordering()
236 private boolean mIsReordering;
237 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
238 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
239 private int mPostReorderingPreZoomInRemainingAnimationCount;
240 private Runnable mPostReorderingPreZoomInRunnable;
241
Adam Cohen7d30a372013-07-01 17:03:59 -0700242 // Convenience/caching
243 private Matrix mTmpInvMatrix = new Matrix();
244 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700245 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700246 private Rect mTmpRect = new Rect();
247 private Rect mAltTmpRect = new Rect();
248
249 // Fling to delete
250 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
251 private float FLING_TO_DELETE_FRICTION = 0.035f;
252 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
253 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
254 protected int mFlingToDeleteThresholdVelocity = -1400;
255 // Drag to delete
256 private boolean mDeferringForDelete = false;
257 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
258 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
259
260 // Drop to delete
261 private View mDeleteDropTarget;
262
263 private boolean mAutoComputePageSpacing = false;
264 private boolean mRecomputePageSpacing = false;
265
266 // Bouncer
267 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700268
John Spurlock77e1f472013-09-11 10:09:51 -0400269 protected final Rect mInsets = new Rect();
270
Michael Jurkafe0ace32013-10-03 01:05:14 -0700271 protected int mFirstChildLeft;
272
Winson Chung86f77532010-08-24 11:08:22 -0700273 public interface PageSwitchListener {
274 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700275 }
276
Winson Chung321e9ee2010-08-09 13:37:56 -0700277 public PagedView(Context context) {
278 this(context, null);
279 }
280
281 public PagedView(Context context, AttributeSet attrs) {
282 this(context, attrs, 0);
283 }
284
285 public PagedView(Context context, AttributeSet attrs, int defStyle) {
286 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700287
Adam Cohen9c4949e2010-10-05 12:27:22 -0700288 TypedArray a = context.obtainStyledAttributes(attrs,
289 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800290 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700291 if (mPageSpacing < 0) {
292 mAutoComputePageSpacing = mRecomputePageSpacing = true;
293 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700294 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800295 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700296 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800297 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700298 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800299 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700300 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800301 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700302 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700303 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700304 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700305 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700306 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700307 a.recycle();
308
Winson Chung321e9ee2010-08-09 13:37:56 -0700309 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700310 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700311 }
312
313 /**
314 * Initializes various states for this workspace.
315 */
Michael Jurka0142d492010-08-25 17:46:15 -0700316 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700317 mDirtyPageContent = new ArrayList<Boolean>();
318 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800319 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700320 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700321 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700322
323 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700324 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700325 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
326 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700327 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800328
Adam Cohen7d30a372013-07-01 17:03:59 -0700329 // Scale the fling-to-delete threshold by the density
330 mFlingToDeleteThresholdVelocity =
331 (int) (mFlingToDeleteThresholdVelocity * mDensity);
332
Adam Cohen265b9a62011-12-07 14:37:18 -0800333 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
334 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
335 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700336 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700337 }
338
Winson Chungd2be3812013-07-16 11:11:32 -0700339 protected void onAttachedToWindow() {
Adam Cohen53805212013-10-01 10:39:23 -0700340 super.onAttachedToWindow();
341
Winson Chungd2be3812013-07-16 11:11:32 -0700342 // Hook up the page indicator
343 ViewGroup parent = (ViewGroup) getParent();
344 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
345 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700346 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700347
Winson Chung7819a562013-09-19 15:55:45 -0700348 ArrayList<PageIndicator.PageMarkerResources> markers =
349 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700350 for (int i = 0; i < getChildCount(); ++i) {
351 markers.add(getPageIndicatorMarker(i));
352 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700353
Winson Chungc58497e2013-09-03 17:48:37 -0700354 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenfbdf4272013-10-09 13:02:21 -0700355
356 OnClickListener listener = getPageIndicatorClickListener();
357 if (listener != null) {
358 mPageIndicator.setOnClickListener(listener);
359 }
Adam Cohen53805212013-10-01 10:39:23 -0700360 mPageIndicator.setContentDescription(getPageIndicatorDescription());
Winson Chungd2be3812013-07-16 11:11:32 -0700361 }
362 }
363
Adam Cohen53805212013-10-01 10:39:23 -0700364 protected String getPageIndicatorDescription() {
365 return getCurrentPageDescription();
366 }
367
368 protected OnClickListener getPageIndicatorClickListener() {
369 return null;
370 }
371
Winson Chungd2be3812013-07-16 11:11:32 -0700372 protected void onDetachedFromWindow() {
373 // Unhook the page indicator
374 mPageIndicator = null;
375 }
376
Adam Cohen7d30a372013-07-01 17:03:59 -0700377 void setDeleteDropTarget(View v) {
378 mDeleteDropTarget = v;
379 }
380
381 // Convenience methods to map points from self to parent and vice versa
382 float[] mapPointFromViewToParent(View v, float x, float y) {
383 mTmpPoint[0] = x;
384 mTmpPoint[1] = y;
385 v.getMatrix().mapPoints(mTmpPoint);
386 mTmpPoint[0] += v.getLeft();
387 mTmpPoint[1] += v.getTop();
388 return mTmpPoint;
389 }
390 float[] mapPointFromParentToView(View v, float x, float y) {
391 mTmpPoint[0] = x - v.getLeft();
392 mTmpPoint[1] = y - v.getTop();
393 v.getMatrix().invert(mTmpInvMatrix);
394 mTmpInvMatrix.mapPoints(mTmpPoint);
395 return mTmpPoint;
396 }
397
398 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700399 if (mDragView != null) {
400 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
401 (mDragViewBaselineLeft - mDragView.getLeft());
402 float y = mLastMotionY - mDownMotionY;
403 mDragView.setTranslationX(x);
404 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700405
Adam Cohenf358a4b2013-07-23 16:47:31 -0700406 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
407 + x + ", " + y);
408 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700409 }
410
411 public void setMinScale(float f) {
412 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700413 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700414 requestLayout();
415 }
416
417 @Override
418 public void setScaleX(float scaleX) {
419 super.setScaleX(scaleX);
420 if (isReordering(true)) {
421 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
422 mLastMotionX = p[0];
423 mLastMotionY = p[1];
424 updateDragViewTranslationDuringDrag();
425 }
426 }
427
428 // Convenience methods to get the actual width/height of the PagedView (since it is measured
429 // to be larger to account for the minimum possible scale)
430 int getViewportWidth() {
431 return mViewport.width();
432 }
433 int getViewportHeight() {
434 return mViewport.height();
435 }
436
437 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
438 // PagedView both horizontally and vertically
439 int getViewportOffsetX() {
440 return (getMeasuredWidth() - getViewportWidth()) / 2;
441 }
442
443 int getViewportOffsetY() {
444 return (getMeasuredHeight() - getViewportHeight()) / 2;
445 }
446
Adam Cohenedb40762013-07-18 16:45:45 -0700447 PageIndicator getPageIndicator() {
448 return mPageIndicator;
449 }
Winson Chung7819a562013-09-19 15:55:45 -0700450 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
451 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700452 }
Adam Cohenedb40762013-07-18 16:45:45 -0700453
Winson Chung86f77532010-08-24 11:08:22 -0700454 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
455 mPageSwitchListener = pageSwitchListener;
456 if (mPageSwitchListener != null) {
457 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700458 }
459 }
460
461 /**
Winson Chung52aee602013-01-30 12:01:02 -0800462 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
463 */
464 public boolean isLayoutRtl() {
465 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
466 }
467
468 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700469 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
470 * out pages.
471 */
472 protected void setDataIsReady() {
473 mIsDataReady = true;
474 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700475
Winson Chungf0ea4d32011-06-06 14:27:16 -0700476 protected boolean isDataReady() {
477 return mIsDataReady;
478 }
479
480 /**
Winson Chung86f77532010-08-24 11:08:22 -0700481 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700482 *
Winson Chung86f77532010-08-24 11:08:22 -0700483 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700484 */
Winson Chung86f77532010-08-24 11:08:22 -0700485 int getCurrentPage() {
486 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700487 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700488
Winson Chung360e63f2012-04-27 13:48:05 -0700489 int getNextPage() {
490 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
491 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700492
Winson Chung86f77532010-08-24 11:08:22 -0700493 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700494 return getChildCount();
495 }
496
Winson Chung86f77532010-08-24 11:08:22 -0700497 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700498 return getChildAt(index);
499 }
500
Adam Cohenae4f1552011-10-20 00:15:42 -0700501 protected int indexToPage(int index) {
502 return index;
503 }
504
Winson Chung321e9ee2010-08-09 13:37:56 -0700505 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800506 * Updates the scroll of the current page immediately to its final scroll position. We use this
507 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
508 * the previous tab page.
509 */
510 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700511 // If the current page is invalid, just reset the scroll position to zero
512 int newX = 0;
513 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700514 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700515 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800516 scrollTo(newX, 0);
517 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800518 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800519 }
520
521 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700522 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
523 * ends, {@link #resumeScrolling()} should be called, along with
524 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
525 */
526 void pauseScrolling() {
527 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700528 }
529
530 /**
531 * Enables scrolling again.
532 * @see #pauseScrolling()
533 */
534 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700535 }
536 /**
Winson Chung86f77532010-08-24 11:08:22 -0700537 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700538 */
Winson Chung86f77532010-08-24 11:08:22 -0700539 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800540 if (!mScroller.isFinished()) {
541 mScroller.abortAnimation();
Adam Cohen97d53112013-10-01 11:07:24 -0700542 // We need to clean up the next page here to avoid computeScrollHelper from
543 // updating current page on the pass.
544 mNextPage = INVALID_PAGE;
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800545 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800546 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
547 // the default
548 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800549 return;
550 }
Adam Cohene61a9a22013-06-11 15:45:31 -0700551 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700552 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700553 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700554 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800555 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700556 }
557
Winson Chung8c87cd82013-07-23 16:20:10 -0700558 /**
559 * The restore page will be set in place of the current page at the next (likely first)
560 * layout.
561 */
562 void setRestorePage(int restorePage) {
563 mRestorePage = restorePage;
564 }
565
Michael Jurka0142d492010-08-25 17:46:15 -0700566 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700567 if (mPageSwitchListener != null) {
568 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700569 }
Winson Chungd2be3812013-07-16 11:11:32 -0700570
571 // Update the page indicator (when we aren't reordering)
572 if (mPageIndicator != null && !isReordering(false)) {
573 mPageIndicator.setActiveMarker(getNextPage());
574 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700575 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800576 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700577 if (!mIsPageMoving) {
578 mIsPageMoving = true;
579 onPageBeginMoving();
580 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700581 }
582
Michael Jurkace7e05f2011-02-01 22:02:35 -0800583 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700584 if (mIsPageMoving) {
585 mIsPageMoving = false;
586 onPageEndMoving();
587 }
Michael Jurka0142d492010-08-25 17:46:15 -0700588 }
589
Adam Cohen26976d92011-03-22 15:33:33 -0700590 protected boolean isPageMoving() {
591 return mIsPageMoving;
592 }
593
Michael Jurka0142d492010-08-25 17:46:15 -0700594 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700595 protected void onPageBeginMoving() {
596 }
597
598 // a method that subclasses can override to add behavior
599 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700600 }
601
Winson Chung321e9ee2010-08-09 13:37:56 -0700602 /**
Winson Chung86f77532010-08-24 11:08:22 -0700603 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700604 *
605 * @param l The listener used to respond to long clicks.
606 */
607 @Override
608 public void setOnLongClickListener(OnLongClickListener l) {
609 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700610 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700611 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700612 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700613 }
Adam Cohen1697b792013-09-17 19:08:21 -0700614 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700615 }
616
617 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800618 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700619 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800620 }
621
622 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700623 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700624 // In free scroll mode, we clamp the scrollX
625 if (mFreeScroll) {
626 x = Math.min(x, mFreeScrollMaxScrollX);
627 x = Math.max(x, mFreeScrollMinScrollX);
628 }
629
Adam Cohen0ffac432013-07-10 11:19:26 -0700630 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800631 mUnboundedScrollX = x;
632
Adam Cohen0ffac432013-07-10 11:19:26 -0700633 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
634 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
635 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800636 super.scrollTo(0, y);
637 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700638 if (isRtl) {
639 overScroll(x - mMaxScrollX);
640 } else {
641 overScroll(x);
642 }
Adam Cohen68d73932010-11-15 10:50:58 -0800643 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700644 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800645 super.scrollTo(mMaxScrollX, y);
646 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700647 if (isRtl) {
648 overScroll(x);
649 } else {
650 overScroll(x - mMaxScrollX);
651 }
Adam Cohen68d73932010-11-15 10:50:58 -0800652 }
653 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800654 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800655 super.scrollTo(x, y);
656 }
657
Michael Jurka0142d492010-08-25 17:46:15 -0700658 mTouchX = x;
659 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700660
661 // Update the last motion events when scrolling
662 if (isReordering(true)) {
663 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
664 mLastMotionX = p[0];
665 mLastMotionY = p[1];
666 updateDragViewTranslationDuringDrag();
667 }
Michael Jurka0142d492010-08-25 17:46:15 -0700668 }
669
Adam Cohen53805212013-10-01 10:39:23 -0700670 private void sendScrollAccessibilityEvent() {
671 AccessibilityManager am =
672 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
673 if (am.isEnabled()) {
674 AccessibilityEvent ev =
675 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
Adam Cohen53805212013-10-01 10:39:23 -0700676 ev.setItemCount(getChildCount());
677 ev.setFromIndex(mCurrentPage);
Adam Cohen53805212013-10-01 10:39:23 -0700678
Alan Viverette254139a2013-10-08 13:13:46 -0700679 final int action;
Adam Cohen53805212013-10-01 10:39:23 -0700680 if (getNextPage() >= mCurrentPage) {
681 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD;
682 } else {
683 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
684 }
685
686 ev.setAction(action);
687 sendAccessibilityEventUnchecked(ev);
688 }
689 }
690
Michael Jurka0142d492010-08-25 17:46:15 -0700691 // we moved this functionality to a helper function so SmoothPagedView can reuse it
692 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700693 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700694 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700695 if (getScrollX() != mScroller.getCurrX()
696 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700697 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700698 float scaleX = mFreeScroll ? getScaleX() : 1f;
699 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
700 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700701 }
Michael Jurka0142d492010-08-25 17:46:15 -0700702 invalidate();
703 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700704 } else if (mNextPage != INVALID_PAGE) {
Adam Cohen53805212013-10-01 10:39:23 -0700705 sendScrollAccessibilityEvent();
706
Winson Chung86f77532010-08-24 11:08:22 -0700707 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700708 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700709 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700710
Winson Chung9c0565f2013-07-19 13:49:06 -0700711 // Load the associated pages if necessary
712 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
713 loadAssociatedPages(mCurrentPage);
714 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
715 }
716
Adam Cohen73aa9752010-11-24 16:26:58 -0800717 // We don't want to trigger a page end moving unless the page has settled
718 // and the user has stopped scrolling
719 if (mTouchState == TOUCH_STATE_REST) {
720 pageEndMoving();
721 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700722
Adam Cohen7d30a372013-07-01 17:03:59 -0700723 onPostReorderingAnimationCompleted();
Adam Cohen53805212013-10-01 10:39:23 -0700724 AccessibilityManager am = (AccessibilityManager)
Adam Cohen0ffac432013-07-10 11:19:26 -0700725 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
Adam Cohen53805212013-10-01 10:39:23 -0700726 if (am.isEnabled()) {
727 // Notify the user when the page changes
728 announceForAccessibility(getCurrentPageDescription());
Adam Cohen0ffac432013-07-10 11:19:26 -0700729 }
Michael Jurka0142d492010-08-25 17:46:15 -0700730 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700731 }
Michael Jurka0142d492010-08-25 17:46:15 -0700732 return false;
733 }
734
735 @Override
736 public void computeScroll() {
737 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700738 }
739
Adam Cohen7d30a372013-07-01 17:03:59 -0700740 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
741 return mTopAlignPageWhenShrinkingForBouncer;
742 }
743
Adam Cohen96d30a12013-07-16 18:13:21 -0700744 public static class LayoutParams extends ViewGroup.LayoutParams {
745 public boolean isFullScreenPage = false;
746
747 /**
748 * {@inheritDoc}
749 */
750 public LayoutParams(int width, int height) {
751 super(width, height);
752 }
753
754 public LayoutParams(ViewGroup.LayoutParams source) {
755 super(source);
756 }
757 }
758
759 protected LayoutParams generateDefaultLayoutParams() {
760 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
761 }
762
Adam Cohenedb40762013-07-18 16:45:45 -0700763 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700764 LayoutParams lp = generateDefaultLayoutParams();
765 lp.isFullScreenPage = true;
766 super.addView(page, 0, lp);
767 }
768
Adam Cohen410f3cd2013-09-22 12:09:32 -0700769 public int getNormalChildHeight() {
770 return mNormalChildHeight;
771 }
772
Winson Chung321e9ee2010-08-09 13:37:56 -0700773 @Override
774 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700775 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700776 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
777 return;
778 }
779
Adam Cohen7d30a372013-07-01 17:03:59 -0700780 // We measure the dimensions of the PagedView to be larger than the pages so that when we
781 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700782 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
783 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
784 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700785 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700786 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
787 // viewport, we can be at most one and a half screens offset once we scale down
788 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700789 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700790
Winson Chungc58497e2013-09-03 17:48:37 -0700791 int parentWidthSize, parentHeightSize;
792 int scaledWidthSize, scaledHeightSize;
793 if (mUseMinScale) {
794 parentWidthSize = (int) (1.5f * maxSize);
795 parentHeightSize = maxSize;
796 scaledWidthSize = (int) (parentWidthSize / mMinScale);
797 scaledHeightSize = (int) (parentHeightSize / mMinScale);
798 } else {
799 scaledWidthSize = widthSize;
800 scaledHeightSize = heightSize;
801 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700802 mViewport.set(0, 0, widthSize, heightSize);
803
804 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
805 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
806 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700807 }
808
Winson Chung8aad6102012-05-11 16:27:49 -0700809 // Return early if we aren't given a proper dimension
810 if (widthSize <= 0 || heightSize <= 0) {
811 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
812 return;
813 }
814
Adam Lesinski6b879f02010-11-04 16:15:23 -0700815 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
816 * of the All apps view on XLarge displays to not take up more space then it needs. Width
817 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
818 * each page to have the same width.
819 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700820 final int verticalPadding = getPaddingTop() + getPaddingBottom();
821 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700822
823 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700824 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700825 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700826 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
827 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
828 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
829 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700830 final int childCount = getChildCount();
831 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700832 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700833 final View child = getPageAt(i);
Vladimir Marko2824b072013-10-04 16:42:17 +0100834 if (child.getVisibility() != GONE) {
835 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700836
Vladimir Marko2824b072013-10-04 16:42:17 +0100837 int childWidthMode;
838 int childHeightMode;
839 int childWidth;
840 int childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700841
Vladimir Marko2824b072013-10-04 16:42:17 +0100842 if (!lp.isFullScreenPage) {
843 if (lp.width == LayoutParams.WRAP_CONTENT) {
844 childWidthMode = MeasureSpec.AT_MOST;
845 } else {
846 childWidthMode = MeasureSpec.EXACTLY;
847 }
848
849 if (lp.height == LayoutParams.WRAP_CONTENT) {
850 childHeightMode = MeasureSpec.AT_MOST;
851 } else {
852 childHeightMode = MeasureSpec.EXACTLY;
853 }
854
855 childWidth = widthSize - horizontalPadding;
856 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
857 mNormalChildHeight = childHeight;
858
Adam Cohen96d30a12013-07-16 18:13:21 -0700859 } else {
860 childWidthMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700861 childHeightMode = MeasureSpec.EXACTLY;
Vladimir Marko2824b072013-10-04 16:42:17 +0100862
863 if (mUseMinScale) {
864 childWidth = getViewportWidth();
865 childHeight = getViewportHeight();
866 } else {
867 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
868 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
869 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700870 }
871
Vladimir Marko2824b072013-10-04 16:42:17 +0100872 final int childWidthMeasureSpec =
873 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
874 final int childHeightMeasureSpec =
875 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
876 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700877 }
Adam Lesinski6b879f02010-11-04 16:15:23 -0700878 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700879 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700880
Winson Chunga128a7b2012-04-30 15:23:15 -0700881 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700882 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700883 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700884 // The gap between pages in the PagedView should be equal to the gap from the page
885 // to the edge of the screen (so it is not visible in the current screen). To
886 // account for unequal padding on each side of the paged view, we take the maximum
887 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700888 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700889 int spacing = Math.max(offset, widthSize - offset -
890 getChildAt(0).getMeasuredWidth());
891 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700892 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700893 }
894 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700895 }
896
Adam Cohen60b07122011-11-14 17:26:06 -0800897 public void setPageSpacing(int pageSpacing) {
898 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700899 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800900 }
901
Michael Jurkafe0ace32013-10-03 01:05:14 -0700902 protected int getFirstChildLeft() {
903 return mFirstChildLeft;
904 }
905
Winson Chung321e9ee2010-08-09 13:37:56 -0700906 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700907 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700908 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700909 return;
910 }
911
Winson Chung785d2eb2011-04-14 16:08:02 -0700912 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700913 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700914
Adam Cohenedb40762013-07-18 16:45:45 -0700915 int screenWidth = getViewportWidth();
916
Adam Cohen7d30a372013-07-01 17:03:59 -0700917 int offsetX = getViewportOffsetX();
918 int offsetY = getViewportOffsetY();
919
920 // Update the viewport offsets
921 mViewport.offset(offsetX, offsetY);
922
Adam Cohen0ffac432013-07-10 11:19:26 -0700923 final boolean isRtl = isLayoutRtl();
924
925 final int startIndex = isRtl ? childCount - 1 : 0;
926 final int endIndex = isRtl ? -1 : childCount;
927 final int delta = isRtl ? -1 : 1;
928
Adam Cohen7d30a372013-07-01 17:03:59 -0700929 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700930
Michael Jurkafe0ace32013-10-03 01:05:14 -0700931 int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700932 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
933 mPageScrolls = new int[getChildCount()];
934 }
935
Adam Cohen0ffac432013-07-10 11:19:26 -0700936 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700937 final View child = getPageAt(i);
Winson Chung321e9ee2010-08-09 13:37:56 -0700938 if (child.getVisibility() != View.GONE) {
Vladimir Marko2824b072013-10-04 16:42:17 +0100939 LayoutParams lp = (LayoutParams) child.getLayoutParams();
940 int childTop;
941 if (lp.isFullScreenPage) {
942 childTop = offsetY;
943 } else {
944 childTop = offsetY + getPaddingTop() + mInsets.top;
945 if (mCenterPagesVertically) {
946 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
947 }
948 }
949
Adam Cohen96d30a12013-07-16 18:13:21 -0700950 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700951 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800952
Winson Chung785d2eb2011-04-14 16:08:02 -0700953 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700954 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800955 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700956
957 // We assume the left and right padding are equal, and hence center the pages
958 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700959 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700960 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
961
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700962 if (i != endIndex - delta) {
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700963 childLeft += childWidth + scrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700964 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700965 childLeft += nextScrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700966 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700967 }
968 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700969
970 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
971 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800972 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700973 setHorizontalScrollBarEnabled(true);
974 mFirstLayout = false;
975 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700976
977 if (childCount > 0) {
978 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700979 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700980 } else {
981 mMaxScrollX = 0;
982 }
983
984 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
985 !mDeferringForDelete) {
Adam Cohen21cd0022013-10-09 18:57:02 -0700986 if (mRestorePage != INVALID_RESTORE_PAGE) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700987 setCurrentPage(mRestorePage);
Adam Cohen21cd0022013-10-09 18:57:02 -0700988 mRestorePage = INVALID_RESTORE_PAGE;
Winson Chung8c87cd82013-07-23 16:20:10 -0700989 } else {
990 setCurrentPage(getNextPage());
991 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700992 }
993 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700994
995 if (isReordering(true)) {
996 updateDragViewTranslationDuringDrag();
997 }
Winson Chunge3193b92010-09-10 11:44:42 -0700998 }
999
Adam Cohenf34bab52010-09-30 14:11:56 -07001000 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -07001001 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1002
1003 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -07001004 for (int i = 0; i < getChildCount(); i++) {
1005 View child = getChildAt(i);
1006 if (child != null) {
1007 float scrollProgress = getScrollProgress(screenCenter, child, i);
1008 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -08001009 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -07001010 }
1011 }
1012 invalidate();
1013 }
Adam Cohenf34bab52010-09-30 14:11:56 -07001014 }
1015
Winson Chungc58497e2013-09-03 17:48:37 -07001016 protected void enablePagedViewAnimations() {
1017 mAllowPagedViewAnimations = true;
1018
1019 }
1020 protected void disablePagedViewAnimations() {
1021 mAllowPagedViewAnimations = false;
1022 }
1023
Winson Chunge3193b92010-09-10 11:44:42 -07001024 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -07001025 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -07001026 // Update the page indicator, we don't update the page indicator as we
1027 // add/remove pages
1028 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -07001029 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -07001030 mPageIndicator.addMarker(pageIndex,
1031 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -07001032 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001033 }
1034
Adam Cohen2591f6a2011-10-25 14:36:40 -07001035 // This ensures that when children are added, they get the correct transforms / alphas
1036 // in accordance with any scroll effects.
1037 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -07001038 mRecomputePageSpacing = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001039 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001040 invalidate();
1041 }
1042
Michael Jurka8b805b12012-04-18 14:23:14 -07001043 @Override
1044 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001045 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001046 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001047 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001048 }
1049
Winson Chungd2be3812013-07-16 11:11:32 -07001050 private void removeMarkerForView(int index) {
1051 // Update the page indicator, we don't update the page indicator as we
1052 // add/remove pages
1053 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001054 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001055 }
1056 }
1057
1058 @Override
1059 public void removeView(View v) {
1060 // XXX: We should find a better way to hook into this before the view
1061 // gets removed form its parent...
1062 removeMarkerForView(indexOfChild(v));
1063 super.removeView(v);
1064 }
1065 @Override
1066 public void removeViewInLayout(View v) {
1067 // XXX: We should find a better way to hook into this before the view
1068 // gets removed form its parent...
1069 removeMarkerForView(indexOfChild(v));
1070 super.removeViewInLayout(v);
1071 }
1072 @Override
1073 public void removeViewAt(int index) {
1074 // XXX: We should find a better way to hook into this before the view
1075 // gets removed form its parent...
1076 removeViewAt(index);
1077 super.removeViewAt(index);
1078 }
1079 @Override
1080 public void removeAllViewsInLayout() {
1081 // Update the page indicator, we don't update the page indicator as we
1082 // add/remove pages
1083 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001084 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001085 }
1086
1087 super.removeAllViewsInLayout();
1088 }
1089
Adam Cohen73894962011-10-31 13:17:17 -07001090 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001091 if (index < 0 || index > getChildCount() - 1) return 0;
1092
Adam Cohenf698c6e2013-07-17 18:44:25 -07001093 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001094
Adam Cohenf698c6e2013-07-17 18:44:25 -07001095 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001096 }
1097
Adam Cohenf358a4b2013-07-23 16:47:31 -07001098 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001099 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001100 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001101 }
1102
Michael Jurkadde558b2011-11-09 22:09:06 -08001103 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001104 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001105 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001106
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001107 range[0] = -1;
1108 range[1] = -1;
1109
Michael Jurkac4fb9172010-09-02 17:19:20 -07001110 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001111 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001112 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001113
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001114 int count = getChildCount();
1115 for (int i = 0; i < count; i++) {
1116 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001117
Winson Chungc9ca2982013-07-19 12:07:38 -07001118 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001119 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001120 if (mTmpIntPoint[0] > viewportWidth) {
1121 if (range[0] == -1) {
1122 continue;
1123 } else {
1124 break;
1125 }
1126 }
1127
Adam Cohen6a678da2013-09-24 10:58:01 -07001128 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001129 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1130 if (mTmpIntPoint[0] < 0) {
1131 if (range[0] == -1) {
1132 continue;
1133 } else {
1134 break;
1135 }
1136 }
1137 curScreen = i;
1138 if (range[0] < 0) {
1139 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001140 }
1141 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001142
1143 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001144 } else {
1145 range[0] = -1;
1146 range[1] = -1;
1147 }
1148 }
1149
Michael Jurka920d7f42012-05-14 16:29:55 -07001150 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001151 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001152 }
1153
Michael Jurkadde558b2011-11-09 22:09:06 -08001154 @Override
1155 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001156 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001157 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1158 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001159 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001160
1161 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001162 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1163 // set it for the next frame
1164 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001165 screenScrolled(screenCenter);
1166 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001167 }
1168
1169 // Find out which screens are visible; as an optimization we only call draw on them
1170 final int pageCount = getChildCount();
1171 if (pageCount > 0) {
1172 getVisiblePages(mTempVisiblePagesRange);
1173 final int leftScreen = mTempVisiblePagesRange[0];
1174 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001175 if (leftScreen != -1 && rightScreen != -1) {
1176 final long drawingTime = getDrawingTime();
1177 // Clip to the bounds
1178 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001179 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1180 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001181
Adam Cohen7d30a372013-07-01 17:03:59 -07001182 // Draw all the children, leaving the drag view for last
1183 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001184 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001185 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001186 if (mForceDrawAllChildrenNextFrame ||
1187 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001188 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001189 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001190 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001191 // Draw the drag view on top (if there is one)
1192 if (mDragView != null) {
1193 drawChild(canvas, mDragView, drawingTime);
1194 }
1195
Michael Jurka5e368ff2012-05-14 23:13:15 -07001196 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001197 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001198 }
Michael Jurka0142d492010-08-25 17:46:15 -07001199 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001200 }
1201
1202 @Override
1203 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001204 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001205 if (page != mCurrentPage || !mScroller.isFinished()) {
1206 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001207 return true;
1208 }
1209 return false;
1210 }
1211
1212 @Override
1213 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001214 int focusablePage;
1215 if (mNextPage != INVALID_PAGE) {
1216 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001217 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001218 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001219 }
Winson Chung86f77532010-08-24 11:08:22 -07001220 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001221 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001222 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001223 }
1224 return false;
1225 }
1226
1227 @Override
1228 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001229 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001230 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001231 if (getCurrentPage() > 0) {
1232 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001233 return true;
1234 }
1235 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001236 if (getCurrentPage() < getPageCount() - 1) {
1237 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001238 return true;
1239 }
1240 }
1241 return super.dispatchUnhandledMove(focused, direction);
1242 }
1243
1244 @Override
1245 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001246 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001247 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001248 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001249 }
1250 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001251 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001252 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001253 }
1254 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001255 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001256 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001257 }
1258 }
1259 }
1260
1261 /**
1262 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001263 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001264 *
Winson Chung86f77532010-08-24 11:08:22 -07001265 * This happens when live folders requery, and if they're off page, they
1266 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001267 */
1268 @Override
1269 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001270 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001271 View v = focused;
1272 while (true) {
1273 if (v == current) {
1274 super.focusableViewAvailable(focused);
1275 return;
1276 }
1277 if (v == this) {
1278 return;
1279 }
1280 ViewParent parent = v.getParent();
1281 if (parent instanceof View) {
1282 v = (View)v.getParent();
1283 } else {
1284 return;
1285 }
1286 }
1287 }
1288
1289 /**
1290 * {@inheritDoc}
1291 */
1292 @Override
1293 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1294 if (disallowIntercept) {
1295 // We need to make sure to cancel our long press if
1296 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001297 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001298 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001299 }
1300 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1301 }
1302
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001303 /**
1304 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1305 */
1306 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001307 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001308 if (isLayoutRtl()) {
1309 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001310 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001311 }
Adam Cohenedb40762013-07-18 16:45:45 -07001312 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001313 }
1314
1315 /**
1316 * Return true if a tap at (x, y) should trigger a flip to the next page.
1317 */
1318 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001319 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001320 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001321 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001322 }
1323 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001324 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001325 }
Winson Chung52aee602013-01-30 12:01:02 -08001326
Adam Cohen7d30a372013-07-01 17:03:59 -07001327 /** Returns whether x and y originated within the buffered viewport */
1328 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1329 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1330 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1331 return mTmpRect.contains(x, y);
1332 }
1333
Winson Chung321e9ee2010-08-09 13:37:56 -07001334 @Override
1335 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001336 if (DISABLE_TOUCH_INTERACTION) {
1337 return false;
1338 }
1339
Winson Chung321e9ee2010-08-09 13:37:56 -07001340 /*
1341 * This method JUST determines whether we want to intercept the motion.
1342 * If we return true, onTouchEvent will be called and we do the actual
1343 * scrolling there.
1344 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001345 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001346
Winson Chung45e1d6e2010-11-09 17:19:49 -08001347 // Skip touch handling if there are no pages to swipe
1348 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1349
Winson Chung321e9ee2010-08-09 13:37:56 -07001350 /*
1351 * Shortcut the most recurring case: the user is in the dragging
1352 * state and he is moving his finger. We want to intercept this
1353 * motion.
1354 */
1355 final int action = ev.getAction();
1356 if ((action == MotionEvent.ACTION_MOVE) &&
1357 (mTouchState == TOUCH_STATE_SCROLLING)) {
1358 return true;
1359 }
1360
Winson Chung321e9ee2010-08-09 13:37:56 -07001361 switch (action & MotionEvent.ACTION_MASK) {
1362 case MotionEvent.ACTION_MOVE: {
1363 /*
1364 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1365 * whether the user has moved far enough from his original down touch.
1366 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001367 if (mActivePointerId != INVALID_POINTER) {
1368 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001369 }
1370 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1371 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1372 // i.e. fall through to the next case (don't break)
1373 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1374 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001375 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 }
1377
1378 case MotionEvent.ACTION_DOWN: {
1379 final float x = ev.getX();
1380 final float y = ev.getY();
1381 // Remember location of down touch
1382 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001383 mDownMotionY = y;
1384 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001385 mLastMotionX = x;
1386 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001387 float[] p = mapPointFromViewToParent(this, x, y);
1388 mParentDownMotionX = p[0];
1389 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001390 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001391 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001392 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001393
Winson Chung321e9ee2010-08-09 13:37:56 -07001394 /*
1395 * If being flinged and user touches the screen, initiate drag;
1396 * otherwise don't. mScroller.isFinished should be false when
1397 * being flinged.
1398 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001399 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001400 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1401 if (finishedScrolling) {
1402 mTouchState = TOUCH_STATE_REST;
1403 mScroller.abortAnimation();
1404 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001405 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1406 mTouchState = TOUCH_STATE_SCROLLING;
1407 } else {
1408 mTouchState = TOUCH_STATE_REST;
1409 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001410 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001411
Winson Chung86f77532010-08-24 11:08:22 -07001412 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001413 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001414 if (!DISABLE_TOUCH_SIDE_PAGES) {
1415 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1416 if (getChildCount() > 0) {
1417 if (hitsPreviousPage(x, y)) {
1418 mTouchState = TOUCH_STATE_PREV_PAGE;
1419 } else if (hitsNextPage(x, y)) {
1420 mTouchState = TOUCH_STATE_NEXT_PAGE;
1421 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001422 }
1423 }
1424 }
1425 break;
1426 }
1427
Winson Chung321e9ee2010-08-09 13:37:56 -07001428 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001429 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001430 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001431 break;
1432
1433 case MotionEvent.ACTION_POINTER_UP:
1434 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001435 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001436 break;
1437 }
1438
1439 /*
1440 * The only time we want to intercept motion events is if we are in the
1441 * drag mode.
1442 */
1443 return mTouchState != TOUCH_STATE_REST;
1444 }
1445
Adam Cohenf8d28232011-02-01 21:47:00 -08001446 protected void determineScrollingStart(MotionEvent ev) {
1447 determineScrollingStart(ev, 1.0f);
1448 }
1449
Winson Chung321e9ee2010-08-09 13:37:56 -07001450 /*
1451 * Determines if we should change the touch state to start scrolling after the
1452 * user moves their touch point too far.
1453 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001454 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001455 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001456 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001457 if (pointerIndex == -1) return;
1458
1459 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001460 final float x = ev.getX(pointerIndex);
1461 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001462 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1463
Winson Chung321e9ee2010-08-09 13:37:56 -07001464 final int xDiff = (int) Math.abs(x - mLastMotionX);
1465 final int yDiff = (int) Math.abs(y - mLastMotionY);
1466
Adam Cohenf8d28232011-02-01 21:47:00 -08001467 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001468 boolean xPaged = xDiff > mPagingTouchSlop;
1469 boolean xMoved = xDiff > touchSlop;
1470 boolean yMoved = yDiff > touchSlop;
1471
Adam Cohenf8d28232011-02-01 21:47:00 -08001472 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001473 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001474 // Scroll if the user moved far enough along the X axis
1475 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001476 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001477 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001478 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001479 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001480 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1481 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001482 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001483 }
1484 }
1485
Adam Cohen7d30a372013-07-01 17:03:59 -07001486 protected float getMaxScrollProgress() {
1487 return 1.0f;
1488 }
1489
Adam Cohenf8d28232011-02-01 21:47:00 -08001490 protected void cancelCurrentPageLongPress() {
1491 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001492 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001493 // Try canceling the long press. It could also have been scheduled
1494 // by a distant descendant, so use the mAllowLongPress flag to block
1495 // everything
1496 final View currentPage = getPageAt(mCurrentPage);
1497 if (currentPage != null) {
1498 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001499 }
1500 }
1501 }
1502
Adam Cohen7d30a372013-07-01 17:03:59 -07001503 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1504 final int halfScreenSize = getViewportWidth() / 2;
1505
1506 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1507 screenCenter = Math.max(halfScreenSize, screenCenter);
1508
1509 return getScrollProgress(screenCenter, v, page);
1510 }
1511
Adam Cohenb5ba0972011-09-07 18:02:31 -07001512 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001513 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001514
Adam Cohen96d30a12013-07-16 18:13:21 -07001515 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001516 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001517
1518 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001519 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1520 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001521 return scrollProgress;
1522 }
1523
Adam Cohenedb40762013-07-18 16:45:45 -07001524 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001525 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001526 return 0;
1527 } else {
1528 return mPageScrolls[index];
1529 }
1530 }
1531
Adam Cohen564a2e72013-10-09 14:47:32 -07001532 // While layout transitions are occurring, a child's position may stray from its baseline
1533 // position. This method returns the magnitude of this stray at any given time.
1534 public int getLayoutTransitionOffsetForPage(int index) {
1535 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1536 return 0;
1537 } else {
1538 View child = getChildAt(index);
1539 int scrollOffset = (getViewportWidth() - child.getMeasuredWidth()) / 2;
1540 int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
1541 return (int) (child.getX() - baselineX);
1542 }
1543 }
1544
Adam Cohene0f66b52010-11-23 15:06:07 -08001545 // This curve determines how the effect of scrolling over the limits of the page dimishes
1546 // as the user pulls further and further from the bounds
1547 private float overScrollInfluenceCurve(float f) {
1548 f -= 1.0f;
1549 return f * f * f + 1.0f;
1550 }
1551
Adam Cohenb5ba0972011-09-07 18:02:31 -07001552 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001553 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001554
1555 // We want to reach the max over scroll effect when the user has
1556 // over scrolled half the size of the screen
1557 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1558
1559 if (f == 0) return;
1560
1561 // Clamp this factor, f, to -1 < f < 1
1562 if (Math.abs(f) >= 1) {
1563 f /= Math.abs(f);
1564 }
1565
1566 int overScrollAmount = (int) Math.round(f * screenSize);
1567 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001568 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001569 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001570 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001571 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001572 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001573 }
1574 invalidate();
1575 }
1576
1577 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001578 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001579
1580 float f = (amount / screenSize);
1581
1582 if (f == 0) return;
1583 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1584
Adam Cohen7bfc9792011-01-28 13:52:37 -08001585 // Clamp this factor, f, to -1 < f < 1
1586 if (Math.abs(f) >= 1) {
1587 f /= Math.abs(f);
1588 }
1589
Adam Cohene0f66b52010-11-23 15:06:07 -08001590 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001591 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001592 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001593 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001594 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001595 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001596 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001597 }
1598 invalidate();
1599 }
1600
Adam Cohenb5ba0972011-09-07 18:02:31 -07001601 protected void overScroll(float amount) {
1602 dampedOverScroll(amount);
1603 }
1604
Michael Jurkac5b262c2011-01-12 20:24:50 -08001605 protected float maxOverScroll() {
1606 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001607 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001608 float f = 1.0f;
1609 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1610 return OVERSCROLL_DAMP_FACTOR * f;
1611 }
1612
Adam Cohenf358a4b2013-07-23 16:47:31 -07001613 protected void enableFreeScroll() {
1614 setEnableFreeScroll(true, -1);
1615 }
1616
1617 protected void disableFreeScroll(int snapPage) {
1618 setEnableFreeScroll(false, snapPage);
1619 }
1620
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001621 void updateFreescrollBounds() {
1622 getOverviewModePages(mTempVisiblePagesRange);
1623 if (isLayoutRtl()) {
1624 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1625 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1626 } else {
1627 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1628 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1629 }
1630 }
1631
Adam Cohenf358a4b2013-07-23 16:47:31 -07001632 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1633 mFreeScroll = freeScroll;
1634
1635 if (snapPage == -1) {
1636 snapPage = getPageNearestToCenterOfScreen();
1637 }
1638
Adam Cohenf358a4b2013-07-23 16:47:31 -07001639 if (!mFreeScroll) {
1640 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001641 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001642 updateFreescrollBounds();
1643 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001644 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1645 setCurrentPage(mTempVisiblePagesRange[0]);
1646 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1647 setCurrentPage(mTempVisiblePagesRange[1]);
1648 }
1649 }
1650
1651 setEnableOverscroll(!freeScroll);
1652 }
1653
1654 private void setEnableOverscroll(boolean enable) {
1655 mAllowOverScroll = enable;
1656 }
1657
1658 int getNearestHoverOverPageIndex() {
1659 if (mDragView != null) {
1660 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1661 + mDragView.getTranslationX());
1662 getOverviewModePages(mTempVisiblePagesRange);
1663 int minDistance = Integer.MAX_VALUE;
1664 int minIndex = indexOfChild(mDragView);
1665 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1666 View page = getPageAt(i);
1667 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1668 int d = Math.abs(dragX - pageX);
1669 if (d < minDistance) {
1670 minIndex = i;
1671 minDistance = d;
1672 }
1673 }
1674 return minIndex;
1675 }
1676 return -1;
1677 }
1678
Winson Chung321e9ee2010-08-09 13:37:56 -07001679 @Override
1680 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001681 if (DISABLE_TOUCH_INTERACTION) {
1682 return false;
1683 }
1684
Adam Cohen1697b792013-09-17 19:08:21 -07001685 super.onTouchEvent(ev);
1686
Winson Chung45e1d6e2010-11-09 17:19:49 -08001687 // Skip touch handling if there are no pages to swipe
1688 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1689
Michael Jurkab8f06722010-10-10 15:58:46 -07001690 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001691
1692 final int action = ev.getAction();
1693
1694 switch (action & MotionEvent.ACTION_MASK) {
1695 case MotionEvent.ACTION_DOWN:
1696 /*
1697 * If being flinged and user touches, stop the fling. isFinished
1698 * will be false if being flinged.
1699 */
1700 if (!mScroller.isFinished()) {
1701 mScroller.abortAnimation();
1702 }
1703
1704 // Remember where the motion event started
1705 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001706 mDownMotionY = mLastMotionY = ev.getY();
1707 mDownScrollX = getScrollX();
1708 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1709 mParentDownMotionX = p[0];
1710 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001711 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001712 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001713 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001714
Michael Jurka0142d492010-08-25 17:46:15 -07001715 if (mTouchState == TOUCH_STATE_SCROLLING) {
1716 pageBeginMoving();
1717 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001718 break;
1719
1720 case MotionEvent.ACTION_MOVE:
1721 if (mTouchState == TOUCH_STATE_SCROLLING) {
1722 // Scroll to follow the motion event
1723 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001724
1725 if (pointerIndex == -1) return true;
1726
Winson Chung321e9ee2010-08-09 13:37:56 -07001727 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001728 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001729
Adam Cohenaefd4e12011-02-14 16:39:38 -08001730 mTotalMotionX += Math.abs(deltaX);
1731
Winson Chungc0844aa2011-02-02 15:25:58 -08001732 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1733 // keep the remainder because we are actually testing if we've moved from the last
1734 // scrolled position (which is discrete).
1735 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001736 mTouchX += deltaX;
1737 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1738 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001739 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001740 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001741 } else {
1742 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001743 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001744 mLastMotionX = x;
1745 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001746 } else {
1747 awakenScrollBars();
1748 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001749 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1750 // Update the last motion position
1751 mLastMotionX = ev.getX();
1752 mLastMotionY = ev.getY();
1753
1754 // Update the parent down so that our zoom animations take this new movement into
1755 // account
1756 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1757 mParentDownMotionX = pt[0];
1758 mParentDownMotionY = pt[1];
1759 updateDragViewTranslationDuringDrag();
1760
1761 // Find the closest page to the touch point
1762 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001763
1764 // Change the drag view if we are hovering over the drop target
1765 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1766 (int) mParentDownMotionX, (int) mParentDownMotionY);
1767 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1768
Adam Cohen7d30a372013-07-01 17:03:59 -07001769 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1770 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1771 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1772 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1773
Adam Cohenf358a4b2013-07-23 16:47:31 -07001774 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1775 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1776 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001777 mTempVisiblePagesRange[0] = 0;
1778 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001779 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001780 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1781 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1782 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1783 mSidePageHoverIndex = pageUnderPointIndex;
1784 mSidePageHoverRunnable = new Runnable() {
1785 @Override
1786 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001787 // Setup the scroll to the correct page before we swap the views
1788 snapToPage(pageUnderPointIndex);
1789
1790 // For each of the pages between the paged view and the drag view,
1791 // animate them from the previous position to the new position in
1792 // the layout (as a result of the drag view moving in the layout)
1793 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1794 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1795 dragViewIndex + 1 : pageUnderPointIndex;
1796 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1797 dragViewIndex - 1 : pageUnderPointIndex;
1798 for (int i = lowerIndex; i <= upperIndex; ++i) {
1799 View v = getChildAt(i);
1800 // dragViewIndex < pageUnderPointIndex, so after we remove the
1801 // drag view all subsequent views to pageUnderPointIndex will
1802 // shift down.
1803 int oldX = getViewportOffsetX() + getChildOffset(i);
1804 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1805
1806 // Animate the view translation from its old position to its new
1807 // position
1808 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1809 if (anim != null) {
1810 anim.cancel();
1811 }
1812
1813 v.setTranslationX(oldX - newX);
1814 anim = new AnimatorSet();
1815 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1816 anim.playTogether(
1817 ObjectAnimator.ofFloat(v, "translationX", 0f));
1818 anim.start();
1819 v.setTag(anim);
1820 }
1821
1822 removeView(mDragView);
1823 onRemoveView(mDragView, false);
1824 addView(mDragView, pageUnderPointIndex);
1825 onAddView(mDragView, pageUnderPointIndex);
1826 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001827 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001828 }
1829 };
1830 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1831 }
1832 } else {
1833 removeCallbacks(mSidePageHoverRunnable);
1834 mSidePageHoverIndex = -1;
1835 }
Adam Cohen564976a2010-10-13 18:52:07 -07001836 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001837 determineScrollingStart(ev);
1838 }
1839 break;
1840
1841 case MotionEvent.ACTION_UP:
1842 if (mTouchState == TOUCH_STATE_SCROLLING) {
1843 final int activePointerId = mActivePointerId;
1844 final int pointerIndex = ev.findPointerIndex(activePointerId);
1845 final float x = ev.getX(pointerIndex);
1846 final VelocityTracker velocityTracker = mVelocityTracker;
1847 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1848 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001849 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001850 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001851 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1852 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001853
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001854 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1855
Adam Cohen00481b32011-11-18 12:03:48 -08001856 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001857 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001858
Adam Cohenf358a4b2013-07-23 16:47:31 -07001859 if (!mFreeScroll) {
1860 // In the case that the page is moved far to one direction and then is flung
1861 // in the opposite direction, we use a threshold to determine whether we should
1862 // just return to the starting page, or if we should skip one further.
1863 boolean returnToOriginalPage = false;
1864 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1865 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1866 returnToOriginalPage = true;
1867 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001868
Adam Cohenf358a4b2013-07-23 16:47:31 -07001869 int finalPage;
1870 // We give flings precedence over large moves, which is why we short-circuit our
1871 // test for a large move if a fling has been registered. That is, a large
1872 // move to the left and fling to the right will register as a fling to the right.
1873 final boolean isRtl = isLayoutRtl();
1874 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1875 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1876 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1877 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1878 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1879 snapToPageWithVelocity(finalPage, velocityX);
1880 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1881 (isFling && isVelocityXLeft)) &&
1882 mCurrentPage < getChildCount() - 1) {
1883 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1884 snapToPageWithVelocity(finalPage, velocityX);
1885 } else {
1886 snapToDestination();
1887 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1888 // at this point we have not moved beyond the touch slop
1889 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1890 // we can just page
1891 int nextPage = Math.max(0, mCurrentPage - 1);
1892 if (nextPage != mCurrentPage) {
1893 snapToPage(nextPage);
1894 } else {
1895 snapToDestination();
1896 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001897 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001898 if (!mScroller.isFinished()) {
1899 mScroller.abortAnimation();
1900 }
1901
1902 float scaleX = getScaleX();
1903 int vX = (int) (-velocityX * scaleX);
1904 int initialScrollX = (int) (getScrollX() * scaleX);
1905
1906 mScroller.fling(initialScrollX,
1907 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1908 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001909 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001910 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001911 // at this point we have not moved beyond the touch slop
1912 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1913 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001914 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1915 if (nextPage != mCurrentPage) {
1916 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001917 } else {
1918 snapToDestination();
1919 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001920 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1921 // Update the last motion position
1922 mLastMotionX = ev.getX();
1923 mLastMotionY = ev.getY();
1924
1925 // Update the parent down so that our zoom animations take this new movement into
1926 // account
1927 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1928 mParentDownMotionX = pt[0];
1929 mParentDownMotionY = pt[1];
1930 updateDragViewTranslationDuringDrag();
1931 boolean handledFling = false;
1932 if (!DISABLE_FLING_TO_DELETE) {
1933 // Check the velocity and see if we are flinging-to-delete
1934 PointF flingToDeleteVector = isFlingingToDelete();
1935 if (flingToDeleteVector != null) {
1936 onFlingToDelete(flingToDeleteVector);
1937 handledFling = true;
1938 }
1939 }
1940 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1941 (int) mParentDownMotionY)) {
1942 onDropToDelete();
1943 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001944 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001945 if (!mCancelTap) {
1946 onUnhandledTap(ev);
1947 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001948 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001949
1950 // Remove the callback to wait for the side page hover timeout
1951 removeCallbacks(mSidePageHoverRunnable);
1952 // End any intermediate reordering states
1953 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001954 break;
1955
1956 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001957 if (mTouchState == TOUCH_STATE_SCROLLING) {
1958 snapToDestination();
1959 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001960 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001961 break;
1962
1963 case MotionEvent.ACTION_POINTER_UP:
1964 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001965 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001966 break;
1967 }
1968
1969 return true;
1970 }
1971
Adam Cohen7d30a372013-07-01 17:03:59 -07001972 public void onFlingToDelete(View v) {}
1973 public void onRemoveView(View v, boolean deletePermanently) {}
1974 public void onRemoveViewAnimationCompleted() {}
1975 public void onAddView(View v, int index) {}
1976
1977 private void resetTouchState() {
1978 releaseVelocityTracker();
1979 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001980 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001981 mTouchState = TOUCH_STATE_REST;
1982 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001983 }
1984
Adam Cohen1697b792013-09-17 19:08:21 -07001985 protected void onUnhandledTap(MotionEvent ev) {
1986 ((Launcher) getContext()).onClick(this);
1987 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001988
Winson Chung185d7162011-02-28 13:47:29 -08001989 @Override
1990 public boolean onGenericMotionEvent(MotionEvent event) {
1991 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1992 switch (event.getAction()) {
1993 case MotionEvent.ACTION_SCROLL: {
1994 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1995 final float vscroll;
1996 final float hscroll;
1997 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1998 vscroll = 0;
1999 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
2000 } else {
2001 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
2002 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
2003 }
2004 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07002005 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
2006 : (hscroll > 0 || vscroll > 0);
2007 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08002008 scrollRight();
2009 } else {
2010 scrollLeft();
2011 }
2012 return true;
2013 }
2014 }
2015 }
2016 }
2017 return super.onGenericMotionEvent(event);
2018 }
2019
Michael Jurkab8f06722010-10-10 15:58:46 -07002020 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
2021 if (mVelocityTracker == null) {
2022 mVelocityTracker = VelocityTracker.obtain();
2023 }
2024 mVelocityTracker.addMovement(ev);
2025 }
2026
2027 private void releaseVelocityTracker() {
2028 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002029 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07002030 mVelocityTracker.recycle();
2031 mVelocityTracker = null;
2032 }
2033 }
2034
Winson Chung321e9ee2010-08-09 13:37:56 -07002035 private void onSecondaryPointerUp(MotionEvent ev) {
2036 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
2037 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
2038 final int pointerId = ev.getPointerId(pointerIndex);
2039 if (pointerId == mActivePointerId) {
2040 // This was our active pointer going up. Choose a new
2041 // active pointer and adjust accordingly.
2042 // TODO: Make this decision more intelligent.
2043 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2044 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
2045 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08002046 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07002047 mActivePointerId = ev.getPointerId(newPointerIndex);
2048 if (mVelocityTracker != null) {
2049 mVelocityTracker.clear();
2050 }
2051 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08002052 }
2053
Winson Chung321e9ee2010-08-09 13:37:56 -07002054 @Override
2055 public void requestChildFocus(View child, View focused) {
2056 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002057 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002058 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002059 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002060 }
2061 }
2062
Winson Chung1908d072011-02-24 18:09:44 -08002063 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002064 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002065 }
2066
Adam Cohen7d30a372013-07-01 17:03:59 -07002067 int getPageNearestToPoint(float x) {
2068 int index = 0;
2069 for (int i = 0; i < getChildCount(); ++i) {
2070 if (x < getChildAt(i).getRight() - getScrollX()) {
2071 return index;
2072 } else {
2073 index++;
2074 }
2075 }
2076 return Math.min(index, getChildCount() - 1);
2077 }
2078
Adam Cohend19d3ca2010-09-15 14:43:42 -07002079 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002080 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002081 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002082 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002083 final int childCount = getChildCount();
2084 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002085 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002086 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002087 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002088 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002089 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2090 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2091 minDistanceFromScreenCenter = distanceFromScreenCenter;
2092 minDistanceFromScreenCenterIndex = i;
2093 }
2094 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002095 return minDistanceFromScreenCenterIndex;
2096 }
2097
2098 protected void snapToDestination() {
2099 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002100 }
2101
Adam Cohene0f66b52010-11-23 15:06:07 -08002102 private static class ScrollInterpolator implements Interpolator {
2103 public ScrollInterpolator() {
2104 }
2105
2106 public float getInterpolation(float t) {
2107 t -= 1.0f;
2108 return t*t*t*t*t + 1;
2109 }
2110 }
2111
2112 // We want the duration of the page snap animation to be influenced by the distance that
2113 // the screen has to travel, however, we don't want this duration to be effected in a
2114 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2115 // of travel has on the overall snap duration.
2116 float distanceInfluenceForSnapDuration(float f) {
2117 f -= 0.5f; // center the values about 0.
2118 f *= 0.3f * Math.PI / 2.0f;
2119 return (float) Math.sin(f);
2120 }
2121
Michael Jurka0142d492010-08-25 17:46:15 -07002122 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002123 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002124 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002125
Adam Cohenedb40762013-07-18 16:45:45 -07002126 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002127 int delta = newX - mUnboundedScrollX;
2128 int duration = 0;
2129
Adam Cohen265b9a62011-12-07 14:37:18 -08002130 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002131 // If the velocity is low enough, then treat this more as an automatic page advance
2132 // as opposed to an apparent physical response to flinging
2133 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2134 return;
2135 }
2136
2137 // Here we compute a "distance" that will be used in the computation of the overall
2138 // snap duration. This is a function of the actual distance that needs to be traveled;
2139 // we keep this value close to half screen size in order to reduce the variance in snap
2140 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002141 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002142 float distance = halfScreenSize + halfScreenSize *
2143 distanceInfluenceForSnapDuration(distanceRatio);
2144
2145 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002146 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002147
2148 // we want the page's snap velocity to approximately match the velocity at which the
2149 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002150 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2151 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002152
2153 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002154 }
2155
2156 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002157 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002158 }
2159
Adam Cohen7d30a372013-07-01 17:03:59 -07002160 protected void snapToPageImmediately(int whichPage) {
2161 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2162 }
2163
Michael Jurka0142d492010-08-25 17:46:15 -07002164 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002165 snapToPage(whichPage, duration, false);
2166 }
2167
2168 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002169 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002170
Adam Cohenedb40762013-07-18 16:45:45 -07002171 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002172 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002173 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002174 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002175 }
2176
2177 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002178 snapToPage(whichPage, delta, duration, false);
2179 }
Michael Jurka0142d492010-08-25 17:46:15 -07002180
Adam Cohen7d30a372013-07-01 17:03:59 -07002181 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2182 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002183 View focusedChild = getFocusedChild();
2184 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002185 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002186 focusedChild.clearFocus();
2187 }
2188
Adam Cohen53805212013-10-01 10:39:23 -07002189 sendScrollAccessibilityEvent();
2190
Michael Jurka0142d492010-08-25 17:46:15 -07002191 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002192 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002193 if (immediate) {
2194 duration = 0;
2195 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002196 duration = Math.abs(delta);
2197 }
2198
Adam Cohenf358a4b2013-07-23 16:47:31 -07002199 if (!mScroller.isFinished()) {
2200 mScroller.abortAnimation();
2201 }
Adam Cohen68d73932010-11-15 10:50:58 -08002202 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002203
Michael Jurka0142d492010-08-25 17:46:15 -07002204 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002205
2206 // Trigger a compute() to finish switching pages if necessary
2207 if (immediate) {
2208 computeScroll();
2209 }
2210
Winson Chung9c0565f2013-07-19 13:49:06 -07002211 // Defer loading associated pages until the scroll settles
2212 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2213
Adam Cohen7d30a372013-07-01 17:03:59 -07002214 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002215 invalidate();
2216 }
2217
Winson Chung321e9ee2010-08-09 13:37:56 -07002218 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002219 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002220 }
2221
2222 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002223 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002224 }
2225
Winson Chung86f77532010-08-24 11:08:22 -07002226 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002227 int result = -1;
2228 if (v != null) {
2229 ViewParent vp = v.getParent();
2230 int count = getChildCount();
2231 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002232 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002233 return i;
2234 }
2235 }
2236 }
2237 return result;
2238 }
2239
2240 /**
2241 * @return True is long presses are still allowed for the current touch
2242 */
2243 public boolean allowLongPress() {
2244 return mAllowLongPress;
2245 }
2246
Adam Cohendbdff6b2013-09-18 19:09:15 -07002247 @Override
2248 public boolean performLongClick() {
2249 mCancelTap = true;
2250 return super.performLongClick();
2251 }
2252
Michael Jurka0142d492010-08-25 17:46:15 -07002253 /**
2254 * Set true to allow long-press events to be triggered, usually checked by
2255 * {@link Launcher} to accept or block dpad-initiated long-presses.
2256 */
2257 public void setAllowLongPress(boolean allowLongPress) {
2258 mAllowLongPress = allowLongPress;
2259 }
2260
Winson Chung321e9ee2010-08-09 13:37:56 -07002261 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002262 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002263
2264 SavedState(Parcelable superState) {
2265 super(superState);
2266 }
2267
2268 private SavedState(Parcel in) {
2269 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002270 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002271 }
2272
2273 @Override
2274 public void writeToParcel(Parcel out, int flags) {
2275 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002276 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002277 }
2278
2279 public static final Parcelable.Creator<SavedState> CREATOR =
2280 new Parcelable.Creator<SavedState>() {
2281 public SavedState createFromParcel(Parcel in) {
2282 return new SavedState(in);
2283 }
2284
2285 public SavedState[] newArray(int size) {
2286 return new SavedState[size];
2287 }
2288 };
2289 }
2290
Winson Chungf314b0e2011-08-16 11:54:27 -07002291 protected void loadAssociatedPages(int page) {
2292 loadAssociatedPages(page, false);
2293 }
2294 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002295 if (mContentIsRefreshable) {
2296 final int count = getChildCount();
2297 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002298 int lowerPageBound = getAssociatedLowerPageBound(page);
2299 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002300 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2301 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002302 // First, clear any pages that should no longer be loaded
2303 for (int i = 0; i < count; ++i) {
2304 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002305 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002306 if (layout.getPageChildCount() > 0) {
2307 layout.removeAllViewsOnPage();
2308 }
2309 mDirtyPageContent.set(i, true);
2310 }
2311 }
2312 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002313 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002314 if ((i != page) && immediateAndOnly) {
2315 continue;
2316 }
Michael Jurka0142d492010-08-25 17:46:15 -07002317 if (lowerPageBound <= i && i <= upperPageBound) {
2318 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002319 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002320 mDirtyPageContent.set(i, false);
2321 }
Winson Chung86f77532010-08-24 11:08:22 -07002322 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002323 }
2324 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002325 }
2326 }
2327
Winson Chunge3193b92010-09-10 11:44:42 -07002328 protected int getAssociatedLowerPageBound(int page) {
2329 return Math.max(0, page - 1);
2330 }
2331 protected int getAssociatedUpperPageBound(int page) {
2332 final int count = getChildCount();
2333 return Math.min(page + 1, count - 1);
2334 }
2335
Winson Chung86f77532010-08-24 11:08:22 -07002336 /**
2337 * This method is called ONLY to synchronize the number of pages that the paged view has.
2338 * To actually fill the pages with information, implement syncPageItems() below. It is
2339 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2340 * and therefore, individual page items do not need to be updated in this method.
2341 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002342 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002343
2344 /**
2345 * This method is called to synchronize the items that are on a particular page. If views on
2346 * the page can be reused, then they should be updated within this method.
2347 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002348 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002349
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002350 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002351 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002352 }
2353 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002354 invalidatePageData(currentPage, false);
2355 }
2356 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002357 if (!mIsDataReady) {
2358 return;
2359 }
2360
Michael Jurka0142d492010-08-25 17:46:15 -07002361 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002362 // Force all scrolling-related behavior to end
2363 mScroller.forceFinished(true);
2364 mNextPage = INVALID_PAGE;
2365
Michael Jurka0142d492010-08-25 17:46:15 -07002366 // Update all the pages
2367 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002368
Winson Chung5a808352011-06-27 19:08:49 -07002369 // We must force a measure after we've loaded the pages to update the content width and
2370 // to determine the full scroll width
2371 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2372 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2373
2374 // Set a new page as the current page if necessary
2375 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002376 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002377 }
2378
Michael Jurka0142d492010-08-25 17:46:15 -07002379 // Mark each of the pages as dirty
2380 final int count = getChildCount();
2381 mDirtyPageContent.clear();
2382 for (int i = 0; i < count; ++i) {
2383 mDirtyPageContent.add(true);
2384 }
2385
2386 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002387 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002388 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002389 }
Adam Cohen06559042013-09-29 18:30:56 -07002390 if (isPageMoving()) {
2391 // If the page is moving, then snap it to the final position to ensure we don't get
2392 // stuck between pages
2393 snapToDestination();
2394 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002395 }
Winson Chung007c6982011-06-14 13:27:53 -07002396
Adam Cohen7d30a372013-07-01 17:03:59 -07002397 // Animate the drag view back to the original position
2398 void animateDragViewToOriginalPosition() {
2399 if (mDragView != null) {
2400 AnimatorSet anim = new AnimatorSet();
2401 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2402 anim.playTogether(
2403 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002404 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2405 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2406 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002407 anim.addListener(new AnimatorListenerAdapter() {
2408 @Override
2409 public void onAnimationEnd(Animator animation) {
2410 onPostReorderingAnimationCompleted();
2411 }
2412 });
2413 anim.start();
2414 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002415 }
2416
Adam Cohen7d30a372013-07-01 17:03:59 -07002417 protected void onStartReordering() {
2418 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2419 mTouchState = TOUCH_STATE_REORDERING;
2420 mIsReordering = true;
2421
Adam Cohen7d30a372013-07-01 17:03:59 -07002422 // We must invalidate to trigger a redraw to update the layers such that the drag view
2423 // is always drawn on top
2424 invalidate();
2425 }
2426
2427 private void onPostReorderingAnimationCompleted() {
2428 // Trigger the callback when reordering has settled
2429 --mPostReorderingPreZoomInRemainingAnimationCount;
2430 if (mPostReorderingPreZoomInRunnable != null &&
2431 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2432 mPostReorderingPreZoomInRunnable.run();
2433 mPostReorderingPreZoomInRunnable = null;
2434 }
2435 }
2436
2437 protected void onEndReordering() {
2438 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002439 }
2440
Adam Cohenf358a4b2013-07-23 16:47:31 -07002441 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002442 int dragViewIndex = indexOfChild(v);
2443
2444 if (mTouchState != TOUCH_STATE_REST) return false;
2445
Adam Cohen7d30a372013-07-01 17:03:59 -07002446 mTempVisiblePagesRange[0] = 0;
2447 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002448 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002449 mReorderingStarted = true;
2450
2451 // Check if we are within the reordering range
2452 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002453 dragViewIndex <= mTempVisiblePagesRange[1]) {
2454 // Find the drag view under the pointer
2455 mDragView = getChildAt(dragViewIndex);
2456 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2457 mDragViewBaselineLeft = mDragView.getLeft();
2458 disableFreeScroll(-1);
2459 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002460 return true;
2461 }
2462 return false;
2463 }
2464
2465 boolean isReordering(boolean testTouchState) {
2466 boolean state = mIsReordering;
2467 if (testTouchState) {
2468 state &= (mTouchState == TOUCH_STATE_REORDERING);
2469 }
2470 return state;
2471 }
2472 void endReordering() {
2473 // For simplicity, we call endReordering sometimes even if reordering was never started.
2474 // In that case, we don't want to do anything.
2475 if (!mReorderingStarted) return;
2476 mReorderingStarted = false;
2477
2478 // If we haven't flung-to-delete the current child, then we just animate the drag view
2479 // back into position
2480 final Runnable onCompleteRunnable = new Runnable() {
2481 @Override
2482 public void run() {
2483 onEndReordering();
2484 }
2485 };
2486 if (!mDeferringForDelete) {
2487 mPostReorderingPreZoomInRunnable = new Runnable() {
2488 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002489 onCompleteRunnable.run();
2490 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002491 };
2492 };
2493
2494 mPostReorderingPreZoomInRemainingAnimationCount =
2495 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2496 // Snap to the current page
2497 snapToPage(indexOfChild(mDragView), 0);
2498 // Animate the drag view back to the front position
2499 animateDragViewToOriginalPosition();
2500 } else {
2501 // Handled in post-delete-animation-callbacks
2502 }
2503 }
2504
Adam Cohen7d30a372013-07-01 17:03:59 -07002505 /*
2506 * Flinging to delete - IN PROGRESS
2507 */
2508 private PointF isFlingingToDelete() {
2509 ViewConfiguration config = ViewConfiguration.get(getContext());
2510 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2511
2512 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2513 // Do a quick dot product test to ensure that we are flinging upwards
2514 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2515 mVelocityTracker.getYVelocity());
2516 PointF upVec = new PointF(0f, -1f);
2517 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2518 (vel.length() * upVec.length()));
2519 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2520 return vel;
2521 }
2522 }
2523 return null;
2524 }
2525
2526 /**
2527 * Creates an animation from the current drag view along its current velocity vector.
2528 * For this animation, the alpha runs for a fixed duration and we update the position
2529 * progressively.
2530 */
2531 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2532 private View mDragView;
2533 private PointF mVelocity;
2534 private Rect mFrom;
2535 private long mPrevTime;
2536 private float mFriction;
2537
2538 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2539
2540 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2541 long startTime, float friction) {
2542 mDragView = dragView;
2543 mVelocity = vel;
2544 mFrom = from;
2545 mPrevTime = startTime;
2546 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2547 }
2548
2549 @Override
2550 public void onAnimationUpdate(ValueAnimator animation) {
2551 float t = ((Float) animation.getAnimatedValue()).floatValue();
2552 long curTime = AnimationUtils.currentAnimationTimeMillis();
2553
2554 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2555 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2556
2557 mDragView.setTranslationX(mFrom.left);
2558 mDragView.setTranslationY(mFrom.top);
2559 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2560
2561 mVelocity.x *= mFriction;
2562 mVelocity.y *= mFriction;
2563 mPrevTime = curTime;
2564 }
2565 };
2566
2567 private static final int ANIM_TAG_KEY = 100;
2568
2569 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2570 return new Runnable() {
2571 @Override
2572 public void run() {
2573 int dragViewIndex = indexOfChild(dragView);
2574
2575 // For each of the pages around the drag view, animate them from the previous
2576 // position to the new position in the layout (as a result of the drag view moving
2577 // in the layout)
2578 // NOTE: We can make an assumption here because we have side-bound pages that we
2579 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002580 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002581 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2582 boolean slideFromLeft = (isLastWidgetPage ||
2583 dragViewIndex > mTempVisiblePagesRange[0]);
2584
2585 // Setup the scroll to the correct page before we swap the views
2586 if (slideFromLeft) {
2587 snapToPageImmediately(dragViewIndex - 1);
2588 }
2589
2590 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2591 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2592 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2593 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2594 ArrayList<Animator> animations = new ArrayList<Animator>();
2595 for (int i = lowerIndex; i <= upperIndex; ++i) {
2596 View v = getChildAt(i);
2597 // dragViewIndex < pageUnderPointIndex, so after we remove the
2598 // drag view all subsequent views to pageUnderPointIndex will
2599 // shift down.
2600 int oldX = 0;
2601 int newX = 0;
2602 if (slideFromLeft) {
2603 if (i == 0) {
2604 // Simulate the page being offscreen with the page spacing
2605 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2606 - mPageSpacing;
2607 } else {
2608 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2609 }
2610 newX = getViewportOffsetX() + getChildOffset(i);
2611 } else {
2612 oldX = getChildOffset(i) - getChildOffset(i - 1);
2613 newX = 0;
2614 }
2615
2616 // Animate the view translation from its old position to its new
2617 // position
2618 AnimatorSet anim = (AnimatorSet) v.getTag();
2619 if (anim != null) {
2620 anim.cancel();
2621 }
2622
2623 // Note: Hacky, but we want to skip any optimizations to not draw completely
2624 // hidden views
2625 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2626 v.setTranslationX(oldX - newX);
2627 anim = new AnimatorSet();
2628 anim.playTogether(
2629 ObjectAnimator.ofFloat(v, "translationX", 0f),
2630 ObjectAnimator.ofFloat(v, "alpha", 1f));
2631 animations.add(anim);
2632 v.setTag(ANIM_TAG_KEY, anim);
2633 }
2634
2635 AnimatorSet slideAnimations = new AnimatorSet();
2636 slideAnimations.playTogether(animations);
2637 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2638 slideAnimations.addListener(new AnimatorListenerAdapter() {
2639 @Override
2640 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002641 mDeferringForDelete = false;
2642 onEndReordering();
2643 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002644 }
2645 });
2646 slideAnimations.start();
2647
2648 removeView(dragView);
2649 onRemoveView(dragView, true);
2650 }
2651 };
2652 }
2653
2654 public void onFlingToDelete(PointF vel) {
2655 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2656
2657 // NOTE: Because it takes time for the first frame of animation to actually be
2658 // called and we expect the animation to be a continuation of the fling, we have
2659 // to account for the time that has elapsed since the fling finished. And since
2660 // we don't have a startDelay, we will always get call to update when we call
2661 // start() (which we want to ignore).
2662 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2663 private int mCount = -1;
2664 private long mStartTime;
2665 private float mOffset;
2666 /* Anonymous inner class ctor */ {
2667 mStartTime = startTime;
2668 }
2669
2670 @Override
2671 public float getInterpolation(float t) {
2672 if (mCount < 0) {
2673 mCount++;
2674 } else if (mCount == 0) {
2675 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2676 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2677 mCount++;
2678 }
2679 return Math.min(1f, mOffset + t);
2680 }
2681 };
2682
2683 final Rect from = new Rect();
2684 final View dragView = mDragView;
2685 from.left = (int) dragView.getTranslationX();
2686 from.top = (int) dragView.getTranslationY();
2687 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2688 from, startTime, FLING_TO_DELETE_FRICTION);
2689
2690 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2691
2692 // Create and start the animation
2693 ValueAnimator mDropAnim = new ValueAnimator();
2694 mDropAnim.setInterpolator(tInterpolator);
2695 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2696 mDropAnim.setFloatValues(0f, 1f);
2697 mDropAnim.addUpdateListener(updateCb);
2698 mDropAnim.addListener(new AnimatorListenerAdapter() {
2699 public void onAnimationEnd(Animator animation) {
2700 onAnimationEndRunnable.run();
2701 }
2702 });
2703 mDropAnim.start();
2704 mDeferringForDelete = true;
2705 }
2706
2707 /* Drag to delete */
2708 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2709 if (mDeleteDropTarget != null) {
2710 mAltTmpRect.set(0, 0, 0, 0);
2711 View parent = (View) mDeleteDropTarget.getParent();
2712 if (parent != null) {
2713 parent.getGlobalVisibleRect(mAltTmpRect);
2714 }
2715 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2716 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2717 return mTmpRect.contains(x, y);
2718 }
2719 return false;
2720 }
2721
2722 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2723
2724 private void onDropToDelete() {
2725 final View dragView = mDragView;
2726
2727 final float toScale = 0f;
2728 final float toAlpha = 0f;
2729
2730 // Create and start the complex animation
2731 ArrayList<Animator> animations = new ArrayList<Animator>();
2732 AnimatorSet motionAnim = new AnimatorSet();
2733 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2734 motionAnim.playTogether(
2735 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2736 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2737 animations.add(motionAnim);
2738
2739 AnimatorSet alphaAnim = new AnimatorSet();
2740 alphaAnim.setInterpolator(new LinearInterpolator());
2741 alphaAnim.playTogether(
2742 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2743 animations.add(alphaAnim);
2744
2745 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2746
2747 AnimatorSet anim = new AnimatorSet();
2748 anim.playTogether(animations);
2749 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2750 anim.addListener(new AnimatorListenerAdapter() {
2751 public void onAnimationEnd(Animator animation) {
2752 onAnimationEndRunnable.run();
2753 }
2754 });
2755 anim.start();
2756
2757 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002758 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002759
2760 /* Accessibility */
2761 @Override
2762 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2763 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002764 info.setScrollable(getPageCount() > 1);
2765 if (getCurrentPage() < getPageCount() - 1) {
2766 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2767 }
2768 if (getCurrentPage() > 0) {
2769 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2770 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002771 }
2772
2773 @Override
Alan Viverette254139a2013-10-08 13:13:46 -07002774 public void sendAccessibilityEvent(int eventType) {
2775 // Don't let the view send real scroll events.
2776 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2777 super.sendAccessibilityEvent(eventType);
2778 }
2779 }
2780
2781 @Override
Winson Chung6a0f57d2011-06-29 20:10:49 -07002782 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2783 super.onInitializeAccessibilityEvent(event);
2784 event.setScrollable(true);
Winson Chung6a0f57d2011-06-29 20:10:49 -07002785 }
2786
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002787 @Override
2788 public boolean performAccessibilityAction(int action, Bundle arguments) {
2789 if (super.performAccessibilityAction(action, arguments)) {
2790 return true;
2791 }
2792 switch (action) {
2793 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2794 if (getCurrentPage() < getPageCount() - 1) {
2795 scrollRight();
2796 return true;
2797 }
2798 } break;
2799 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2800 if (getCurrentPage() > 0) {
2801 scrollLeft();
2802 return true;
2803 }
2804 } break;
2805 }
2806 return false;
2807 }
2808
Adam Cohen0ffac432013-07-10 11:19:26 -07002809 protected String getCurrentPageDescription() {
2810 return String.format(getContext().getString(R.string.default_scroll_format),
2811 getNextPage() + 1, getChildCount());
2812 }
2813
Winson Chungd11265e2011-08-30 13:37:23 -07002814 @Override
2815 public boolean onHoverEvent(android.view.MotionEvent event) {
2816 return true;
2817 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002818}