blob: 2a339c0394c521e03ab4e23fc03c2bc858e63c31 [file] [log] [blame]
Winson Chung321e9ee2010-08-09 13:37:56 -07001/*
Adam Cohen7d30a372013-07-01 17:03:59 -07002 * Copyright (C) 2012 The Android Open Source Project
Winson Chung321e9ee2010-08-09 13:37:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Daniel Sandler325dc232013-06-05 22:57:57 -040017package com.android.launcher3;
Winson Chung321e9ee2010-08-09 13:37:56 -070018
Winson Chung228a0fa2011-01-26 22:14:13 -080019import android.animation.Animator;
Winson Chung228a0fa2011-01-26 22:14:13 -080020import android.animation.AnimatorListenerAdapter;
Adam Cohen7d30a372013-07-01 17:03:59 -070021import android.animation.AnimatorSet;
22import android.animation.ObjectAnimator;
23import android.animation.TimeInterpolator;
Winson Chungbb6f6a52011-07-25 17:55:44 -070024import android.animation.ValueAnimator;
Adam Cohen7d30a372013-07-01 17:03:59 -070025import android.animation.ValueAnimator.AnimatorUpdateListener;
Winson Chung321e9ee2010-08-09 13:37:56 -070026import android.content.Context;
Adam Cohen9c4949e2010-10-05 12:27:22 -070027import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070028import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070029import android.graphics.Matrix;
30import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070031import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070032import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070033import android.os.Parcel;
34import android.os.Parcelable;
Adam Cohen53805212013-10-01 10:39:23 -070035import android.support.v4.view.accessibility.AccessibilityEventCompat;
Winson Chung321e9ee2010-08-09 13:37:56 -070036import android.util.AttributeSet;
Adam Cohen7d30a372013-07-01 17:03:59 -070037import android.util.DisplayMetrics;
Winson Chung785d2eb2011-04-14 16:08:02 -070038import android.util.Log;
Winson Chung185d7162011-02-28 13:47:29 -080039import android.view.InputDevice;
40import android.view.KeyEvent;
Winson Chung321e9ee2010-08-09 13:37:56 -070041import android.view.MotionEvent;
42import android.view.VelocityTracker;
43import android.view.View;
44import android.view.ViewConfiguration;
45import android.view.ViewGroup;
46import android.view.ViewParent;
Winson Chung6a0f57d2011-06-29 20:10:49 -070047import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070048import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070049import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070050import android.view.animation.AnimationUtils;
51import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080052import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070053import android.view.animation.LinearInterpolator;
Winson Chung321e9ee2010-08-09 13:37:56 -070054import android.widget.Scroller;
55
Winson Chung6a0f57d2011-06-29 20:10:49 -070056import java.util.ArrayList;
57
Winson Chungc58497e2013-09-03 17:48:37 -070058interface Page {
59 public int getPageChildCount();
60 public View getChildOnPageAt(int i);
61 public void removeAllViewsOnPage();
62 public void removeViewOnPageAt(int i);
63 public int indexOfChildOnPage(View v);
64}
65
Winson Chung321e9ee2010-08-09 13:37:56 -070066/**
67 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070068 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070069 */
Michael Jurka8b805b12012-04-18 14:23:14 -070070public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070071 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070072 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070073 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070074
Winson Chung86f77532010-08-24 11:08:22 -070075 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070076 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070077
Adam Cohen7d30a372013-07-01 17:03:59 -070078 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070079 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070080 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070081
Adam Cohenb5ba0972011-09-07 18:02:31 -070082 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070083 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080084
Adam Cohenb64cb5a2011-02-15 13:53:42 -080085 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080086 // The page is moved more than halfway, automatically move to the next page on touch up.
87 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080088
Adam Cohen265b9a62011-12-07 14:37:18 -080089 // The following constants need to be scaled based on density. The scaled versions will be
90 // assigned to the corresponding member variables below.
91 private static final int FLING_THRESHOLD_VELOCITY = 500;
92 private static final int MIN_SNAP_VELOCITY = 1500;
93 private static final int MIN_FLING_VELOCITY = 250;
94
Adam Cohen7d30a372013-07-01 17:03:59 -070095 // We are disabling touch interaction of the widget region for factory ROM.
96 private static final boolean DISABLE_TOUCH_INTERACTION = false;
Adam Cohenf358a4b2013-07-23 16:47:31 -070097 private static final boolean DISABLE_TOUCH_SIDE_PAGES = true;
Adam Cohendedbd962013-07-11 14:21:49 -070098 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070099
Adam Cohenf358a4b2013-07-23 16:47:31 -0700100 private boolean mFreeScroll = false;
101 private int mFreeScrollMinScrollX = -1;
102 private int mFreeScrollMaxScrollX = -1;
103
Winson Chung8aad6102012-05-11 16:27:49 -0700104 static final int AUTOMATIC_PAGE_SPACING = -1;
105
Adam Cohen265b9a62011-12-07 14:37:18 -0800106 protected int mFlingThresholdVelocity;
107 protected int mMinFlingVelocity;
108 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -0700109
Adam Cohenb5ba0972011-09-07 18:02:31 -0700110 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700111 protected float mSmoothingTime;
112 protected float mTouchX;
113
114 protected boolean mFirstLayout = true;
Adam Cohen410f3cd2013-09-22 12:09:32 -0700115 private int mNormalChildHeight;
Michael Jurka0142d492010-08-25 17:46:15 -0700116
117 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700118 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700119 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700120
Michael Jurka0142d492010-08-25 17:46:15 -0700121 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800122 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700123 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700124 private VelocityTracker mVelocityTracker;
125
Adam Cohen7d30a372013-07-01 17:03:59 -0700126 private float mParentDownMotionX;
127 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700128 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700129 private float mDownMotionY;
130 private float mDownScrollX;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700131 private float mDragViewBaselineLeft;
Michael Jurka7426c422010-11-11 15:23:47 -0800132 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800133 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800134 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800135 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700136 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700137
Adam Cohendbdff6b2013-09-18 19:09:15 -0700138 private boolean mCancelTap;
139
Adam Cohenedb40762013-07-18 16:45:45 -0700140 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700141
Michael Jurka0142d492010-08-25 17:46:15 -0700142 protected final static int TOUCH_STATE_REST = 0;
143 protected final static int TOUCH_STATE_SCROLLING = 1;
144 protected final static int TOUCH_STATE_PREV_PAGE = 2;
145 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700146 protected final static int TOUCH_STATE_REORDERING = 4;
147
Adam Cohene45440e2010-10-14 18:33:38 -0700148 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700149
Michael Jurka0142d492010-08-25 17:46:15 -0700150 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700151 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700152
Michael Jurka0142d492010-08-25 17:46:15 -0700153 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700154
Michael Jurka7426c422010-11-11 15:23:47 -0800155 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700156 private int mPagingTouchSlop;
157 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700158 protected int mPageSpacing;
159 protected int mPageLayoutPaddingTop;
160 protected int mPageLayoutPaddingBottom;
161 protected int mPageLayoutPaddingLeft;
162 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700163 protected int mPageLayoutWidthGap;
164 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700165 protected int mCellCountX = 0;
166 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700167 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800168 protected boolean mAllowOverScroll = true;
169 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800170 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700171 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700172
Michael Jurka8b805b12012-04-18 14:23:14 -0700173 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800174 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
175 // the screens from continuing to translate beyond the normal bounds.
176 protected int mOverScrollX;
177
Michael Jurka5f1c5092010-09-03 14:15:02 -0700178 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700179
Michael Jurka5f1c5092010-09-03 14:15:02 -0700180 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700181
Winson Chung86f77532010-08-24 11:08:22 -0700182 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700183
Michael Jurkae326f182011-11-21 14:05:46 -0800184 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700185
Michael Jurka0142d492010-08-25 17:46:15 -0700186 // If true, syncPages and syncPageItems will be called to refresh pages
187 protected boolean mContentIsRefreshable = true;
188
189 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700190 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700191
192 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
193 // to switch to a new page
194 protected boolean mUsePagingTouchSlop = true;
195
Michael Jurka8b805b12012-04-18 14:23:14 -0700196 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700197 // (SmoothPagedView does this)
198 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700199 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700200
Patrick Dubroy1262e362010-10-06 15:49:50 -0700201 protected boolean mIsPageMoving = false;
202
Winson Chungf0ea4d32011-06-06 14:27:16 -0700203 // All syncs and layout passes are deferred until data is ready.
204 protected boolean mIsDataReady = false;
205
Adam Cohen7d30a372013-07-01 17:03:59 -0700206 protected boolean mAllowLongPress = true;
207
Winson Chungd2be3812013-07-16 11:11:32 -0700208 // Page Indicator
209 private int mPageIndicatorViewId;
210 private PageIndicator mPageIndicator;
Winson Chungc58497e2013-09-03 17:48:37 -0700211 private boolean mAllowPagedViewAnimations = true;
Winson Chung007c6982011-06-14 13:27:53 -0700212
Adam Cohen7d30a372013-07-01 17:03:59 -0700213 // The viewport whether the pages are to be contained (the actual view may be larger than the
214 // viewport)
215 private Rect mViewport = new Rect();
216
217 // Reordering
218 // We use the min scale to determine how much to expand the actually PagedView measured
219 // dimensions such that when we are zoomed out, the view is not clipped
220 private int REORDERING_DROP_REPOSITION_DURATION = 200;
221 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
222 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
Adam Cohenf358a4b2013-07-23 16:47:31 -0700223 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 80;
Adam Cohen7d30a372013-07-01 17:03:59 -0700224 private float mMinScale = 1f;
Winson Chungc58497e2013-09-03 17:48:37 -0700225 private boolean mUseMinScale = false;
Adam Cohen7d30a372013-07-01 17:03:59 -0700226 protected View mDragView;
227 protected AnimatorSet mZoomInOutAnim;
228 private Runnable mSidePageHoverRunnable;
229 private int mSidePageHoverIndex = -1;
230 // This variable's scope is only for the duration of startReordering() and endReordering()
231 private boolean mReorderingStarted = false;
232 // This variable's scope is for the duration of startReordering() and after the zoomIn()
233 // animation after endReordering()
234 private boolean mIsReordering;
235 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
236 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
237 private int mPostReorderingPreZoomInRemainingAnimationCount;
238 private Runnable mPostReorderingPreZoomInRunnable;
239
Adam Cohen7d30a372013-07-01 17:03:59 -0700240 // Convenience/caching
241 private Matrix mTmpInvMatrix = new Matrix();
242 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700243 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700244 private Rect mTmpRect = new Rect();
245 private Rect mAltTmpRect = new Rect();
246
247 // Fling to delete
248 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
249 private float FLING_TO_DELETE_FRICTION = 0.035f;
250 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
251 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
252 protected int mFlingToDeleteThresholdVelocity = -1400;
253 // Drag to delete
254 private boolean mDeferringForDelete = false;
255 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
256 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
257
258 // Drop to delete
259 private View mDeleteDropTarget;
260
261 private boolean mAutoComputePageSpacing = false;
262 private boolean mRecomputePageSpacing = false;
263
264 // Bouncer
265 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700266
John Spurlock77e1f472013-09-11 10:09:51 -0400267 protected final Rect mInsets = new Rect();
268
Michael Jurkafe0ace32013-10-03 01:05:14 -0700269 protected int mFirstChildLeft;
270
Winson Chung86f77532010-08-24 11:08:22 -0700271 public interface PageSwitchListener {
272 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700273 }
274
Winson Chung321e9ee2010-08-09 13:37:56 -0700275 public PagedView(Context context) {
276 this(context, null);
277 }
278
279 public PagedView(Context context, AttributeSet attrs) {
280 this(context, attrs, 0);
281 }
282
283 public PagedView(Context context, AttributeSet attrs, int defStyle) {
284 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700285
Adam Cohen9c4949e2010-10-05 12:27:22 -0700286 TypedArray a = context.obtainStyledAttributes(attrs,
287 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800288 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700289 if (mPageSpacing < 0) {
290 mAutoComputePageSpacing = mRecomputePageSpacing = true;
291 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800293 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700294 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800295 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700296 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800297 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700298 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800299 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700300 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700301 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700302 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700303 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700304 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700305 a.recycle();
306
Winson Chung321e9ee2010-08-09 13:37:56 -0700307 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700308 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700309 }
310
311 /**
312 * Initializes various states for this workspace.
313 */
Michael Jurka0142d492010-08-25 17:46:15 -0700314 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700315 mDirtyPageContent = new ArrayList<Boolean>();
316 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800317 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700318 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700319 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700320
321 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700322 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700323 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
324 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700325 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800326
Adam Cohen7d30a372013-07-01 17:03:59 -0700327 // Scale the fling-to-delete threshold by the density
328 mFlingToDeleteThresholdVelocity =
329 (int) (mFlingToDeleteThresholdVelocity * mDensity);
330
Adam Cohen265b9a62011-12-07 14:37:18 -0800331 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
332 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
333 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700334 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700335 }
336
Winson Chungd2be3812013-07-16 11:11:32 -0700337 protected void onAttachedToWindow() {
Adam Cohen53805212013-10-01 10:39:23 -0700338 super.onAttachedToWindow();
339
Winson Chungd2be3812013-07-16 11:11:32 -0700340 // Hook up the page indicator
341 ViewGroup parent = (ViewGroup) getParent();
342 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
343 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
Winson Chungc58497e2013-09-03 17:48:37 -0700344 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chung82dfe582013-07-26 15:07:49 -0700345
Winson Chung7819a562013-09-19 15:55:45 -0700346 ArrayList<PageIndicator.PageMarkerResources> markers =
347 new ArrayList<PageIndicator.PageMarkerResources>();
Winson Chung82dfe582013-07-26 15:07:49 -0700348 for (int i = 0; i < getChildCount(); ++i) {
349 markers.add(getPageIndicatorMarker(i));
350 }
Adam Cohenf358a4b2013-07-23 16:47:31 -0700351
Winson Chungc58497e2013-09-03 17:48:37 -0700352 mPageIndicator.addMarkers(markers, mAllowPagedViewAnimations);
Adam Cohenfbdf4272013-10-09 13:02:21 -0700353
354 OnClickListener listener = getPageIndicatorClickListener();
355 if (listener != null) {
356 mPageIndicator.setOnClickListener(listener);
357 }
Adam Cohen53805212013-10-01 10:39:23 -0700358 mPageIndicator.setContentDescription(getPageIndicatorDescription());
Winson Chungd2be3812013-07-16 11:11:32 -0700359 }
360 }
361
Adam Cohen53805212013-10-01 10:39:23 -0700362 protected String getPageIndicatorDescription() {
363 return getCurrentPageDescription();
364 }
365
366 protected OnClickListener getPageIndicatorClickListener() {
367 return null;
368 }
369
Winson Chungd2be3812013-07-16 11:11:32 -0700370 protected void onDetachedFromWindow() {
371 // Unhook the page indicator
372 mPageIndicator = null;
373 }
374
Adam Cohen7d30a372013-07-01 17:03:59 -0700375 void setDeleteDropTarget(View v) {
376 mDeleteDropTarget = v;
377 }
378
379 // Convenience methods to map points from self to parent and vice versa
380 float[] mapPointFromViewToParent(View v, float x, float y) {
381 mTmpPoint[0] = x;
382 mTmpPoint[1] = y;
383 v.getMatrix().mapPoints(mTmpPoint);
384 mTmpPoint[0] += v.getLeft();
385 mTmpPoint[1] += v.getTop();
386 return mTmpPoint;
387 }
388 float[] mapPointFromParentToView(View v, float x, float y) {
389 mTmpPoint[0] = x - v.getLeft();
390 mTmpPoint[1] = y - v.getTop();
391 v.getMatrix().invert(mTmpInvMatrix);
392 mTmpInvMatrix.mapPoints(mTmpPoint);
393 return mTmpPoint;
394 }
395
396 void updateDragViewTranslationDuringDrag() {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700397 if (mDragView != null) {
398 float x = (mLastMotionX - mDownMotionX) + (getScrollX() - mDownScrollX) +
399 (mDragViewBaselineLeft - mDragView.getLeft());
400 float y = mLastMotionY - mDownMotionY;
401 mDragView.setTranslationX(x);
402 mDragView.setTranslationY(y);
Adam Cohen7d30a372013-07-01 17:03:59 -0700403
Adam Cohenf358a4b2013-07-23 16:47:31 -0700404 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): "
405 + x + ", " + y);
406 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700407 }
408
409 public void setMinScale(float f) {
410 mMinScale = f;
Winson Chungc58497e2013-09-03 17:48:37 -0700411 mUseMinScale = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700412 requestLayout();
413 }
414
415 @Override
416 public void setScaleX(float scaleX) {
417 super.setScaleX(scaleX);
418 if (isReordering(true)) {
419 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
420 mLastMotionX = p[0];
421 mLastMotionY = p[1];
422 updateDragViewTranslationDuringDrag();
423 }
424 }
425
426 // Convenience methods to get the actual width/height of the PagedView (since it is measured
427 // to be larger to account for the minimum possible scale)
428 int getViewportWidth() {
429 return mViewport.width();
430 }
431 int getViewportHeight() {
432 return mViewport.height();
433 }
434
435 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
436 // PagedView both horizontally and vertically
437 int getViewportOffsetX() {
438 return (getMeasuredWidth() - getViewportWidth()) / 2;
439 }
440
441 int getViewportOffsetY() {
442 return (getMeasuredHeight() - getViewportHeight()) / 2;
443 }
444
Adam Cohenedb40762013-07-18 16:45:45 -0700445 PageIndicator getPageIndicator() {
446 return mPageIndicator;
447 }
Winson Chung7819a562013-09-19 15:55:45 -0700448 protected PageIndicator.PageMarkerResources getPageIndicatorMarker(int pageIndex) {
449 return new PageIndicator.PageMarkerResources();
Winson Chung82dfe582013-07-26 15:07:49 -0700450 }
Adam Cohenedb40762013-07-18 16:45:45 -0700451
Winson Chung86f77532010-08-24 11:08:22 -0700452 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
453 mPageSwitchListener = pageSwitchListener;
454 if (mPageSwitchListener != null) {
455 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700456 }
457 }
458
459 /**
Winson Chung52aee602013-01-30 12:01:02 -0800460 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
461 */
462 public boolean isLayoutRtl() {
463 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
464 }
465
466 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700467 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
468 * out pages.
469 */
470 protected void setDataIsReady() {
471 mIsDataReady = true;
472 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700473
Winson Chungf0ea4d32011-06-06 14:27:16 -0700474 protected boolean isDataReady() {
475 return mIsDataReady;
476 }
477
478 /**
Winson Chung86f77532010-08-24 11:08:22 -0700479 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700480 *
Winson Chung86f77532010-08-24 11:08:22 -0700481 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700482 */
Winson Chung86f77532010-08-24 11:08:22 -0700483 int getCurrentPage() {
484 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700485 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700486
Winson Chung360e63f2012-04-27 13:48:05 -0700487 int getNextPage() {
488 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
489 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700490
Winson Chung86f77532010-08-24 11:08:22 -0700491 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700492 return getChildCount();
493 }
494
Winson Chung86f77532010-08-24 11:08:22 -0700495 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700496 return getChildAt(index);
497 }
498
Adam Cohenae4f1552011-10-20 00:15:42 -0700499 protected int indexToPage(int index) {
500 return index;
501 }
502
Winson Chung321e9ee2010-08-09 13:37:56 -0700503 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800504 * Updates the scroll of the current page immediately to its final scroll position. We use this
505 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
506 * the previous tab page.
507 */
508 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700509 // If the current page is invalid, just reset the scroll position to zero
510 int newX = 0;
511 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700512 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700513 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800514 scrollTo(newX, 0);
515 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800516 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800517 }
518
519 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700520 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
521 * ends, {@link #resumeScrolling()} should be called, along with
522 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
523 */
524 void pauseScrolling() {
525 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700526 }
527
528 /**
529 * Enables scrolling again.
530 * @see #pauseScrolling()
531 */
532 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700533 }
534 /**
Winson Chung86f77532010-08-24 11:08:22 -0700535 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700536 */
Winson Chung86f77532010-08-24 11:08:22 -0700537 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800538 if (!mScroller.isFinished()) {
539 mScroller.abortAnimation();
Adam Cohen97d53112013-10-01 11:07:24 -0700540 // We need to clean up the next page here to avoid computeScrollHelper from
541 // updating current page on the pass.
542 mNextPage = INVALID_PAGE;
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800543 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800544 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
545 // the default
546 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800547 return;
548 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700549
Adam Cohene61a9a22013-06-11 15:45:31 -0700550 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700551 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700552 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700553 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800554 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700555 }
556
Winson Chung8c87cd82013-07-23 16:20:10 -0700557 /**
558 * The restore page will be set in place of the current page at the next (likely first)
559 * layout.
560 */
561 void setRestorePage(int restorePage) {
562 mRestorePage = restorePage;
563 }
564
Michael Jurka0142d492010-08-25 17:46:15 -0700565 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700566 if (mPageSwitchListener != null) {
567 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700568 }
Winson Chungd2be3812013-07-16 11:11:32 -0700569
570 // Update the page indicator (when we aren't reordering)
571 if (mPageIndicator != null && !isReordering(false)) {
572 mPageIndicator.setActiveMarker(getNextPage());
573 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700574 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800575 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700576 if (!mIsPageMoving) {
577 mIsPageMoving = true;
578 onPageBeginMoving();
579 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700580 }
581
Michael Jurkace7e05f2011-02-01 22:02:35 -0800582 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700583 if (mIsPageMoving) {
584 mIsPageMoving = false;
585 onPageEndMoving();
586 }
Michael Jurka0142d492010-08-25 17:46:15 -0700587 }
588
Adam Cohen26976d92011-03-22 15:33:33 -0700589 protected boolean isPageMoving() {
590 return mIsPageMoving;
591 }
592
Michael Jurka0142d492010-08-25 17:46:15 -0700593 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700594 protected void onPageBeginMoving() {
595 }
596
597 // a method that subclasses can override to add behavior
598 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700599 }
600
Winson Chung321e9ee2010-08-09 13:37:56 -0700601 /**
Winson Chung86f77532010-08-24 11:08:22 -0700602 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700603 *
604 * @param l The listener used to respond to long clicks.
605 */
606 @Override
607 public void setOnLongClickListener(OnLongClickListener l) {
608 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700609 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700610 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700611 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700612 }
Adam Cohen1697b792013-09-17 19:08:21 -0700613 super.setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700614 }
615
616 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800617 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700618 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800619 }
620
621 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700622 public void scrollTo(int x, int y) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700623 // In free scroll mode, we clamp the scrollX
624 if (mFreeScroll) {
625 x = Math.min(x, mFreeScrollMaxScrollX);
626 x = Math.max(x, mFreeScrollMinScrollX);
627 }
628
Adam Cohen0ffac432013-07-10 11:19:26 -0700629 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800630 mUnboundedScrollX = x;
631
Adam Cohen0ffac432013-07-10 11:19:26 -0700632 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
633 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
634 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800635 super.scrollTo(0, y);
636 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700637 if (isRtl) {
638 overScroll(x - mMaxScrollX);
639 } else {
640 overScroll(x);
641 }
Adam Cohen68d73932010-11-15 10:50:58 -0800642 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700643 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800644 super.scrollTo(mMaxScrollX, y);
645 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700646 if (isRtl) {
647 overScroll(x);
648 } else {
649 overScroll(x - mMaxScrollX);
650 }
Adam Cohen68d73932010-11-15 10:50:58 -0800651 }
652 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800653 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800654 super.scrollTo(x, y);
655 }
656
Michael Jurka0142d492010-08-25 17:46:15 -0700657 mTouchX = x;
658 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700659
660 // Update the last motion events when scrolling
661 if (isReordering(true)) {
662 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
663 mLastMotionX = p[0];
664 mLastMotionY = p[1];
665 updateDragViewTranslationDuringDrag();
666 }
Michael Jurka0142d492010-08-25 17:46:15 -0700667 }
668
Adam Cohen53805212013-10-01 10:39:23 -0700669 private void sendScrollAccessibilityEvent() {
670 AccessibilityManager am =
671 (AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
672 if (am.isEnabled()) {
673 AccessibilityEvent ev =
674 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
Adam Cohen53805212013-10-01 10:39:23 -0700675 ev.setItemCount(getChildCount());
676 ev.setFromIndex(mCurrentPage);
Adam Cohen53805212013-10-01 10:39:23 -0700677
Alan Viverette254139a2013-10-08 13:13:46 -0700678 final int action;
Adam Cohen53805212013-10-01 10:39:23 -0700679 if (getNextPage() >= mCurrentPage) {
680 action = AccessibilityNodeInfo.ACTION_SCROLL_FORWARD;
681 } else {
682 action = AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD;
683 }
684
685 ev.setAction(action);
686 sendAccessibilityEventUnchecked(ev);
687 }
688 }
689
Michael Jurka0142d492010-08-25 17:46:15 -0700690 // we moved this functionality to a helper function so SmoothPagedView can reuse it
691 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700692 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700693 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700694 if (getScrollX() != mScroller.getCurrX()
695 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700696 || mOverScrollX != mScroller.getCurrX()) {
Adam Cohenf358a4b2013-07-23 16:47:31 -0700697 float scaleX = mFreeScroll ? getScaleX() : 1f;
698 int scrollX = (int) (mScroller.getCurrX() * (1 / scaleX));
699 scrollTo(scrollX, mScroller.getCurrY());
Winson Chung557d6ed2011-07-08 15:34:52 -0700700 }
Michael Jurka0142d492010-08-25 17:46:15 -0700701 invalidate();
702 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700703 } else if (mNextPage != INVALID_PAGE) {
Adam Cohen53805212013-10-01 10:39:23 -0700704 sendScrollAccessibilityEvent();
705
Winson Chung86f77532010-08-24 11:08:22 -0700706 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700707 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700708 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700709
Winson Chung9c0565f2013-07-19 13:49:06 -0700710 // Load the associated pages if necessary
711 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
712 loadAssociatedPages(mCurrentPage);
713 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
714 }
715
Adam Cohen73aa9752010-11-24 16:26:58 -0800716 // We don't want to trigger a page end moving unless the page has settled
717 // and the user has stopped scrolling
718 if (mTouchState == TOUCH_STATE_REST) {
719 pageEndMoving();
720 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700721
Adam Cohen7d30a372013-07-01 17:03:59 -0700722 onPostReorderingAnimationCompleted();
Adam Cohen53805212013-10-01 10:39:23 -0700723 AccessibilityManager am = (AccessibilityManager)
Adam Cohen0ffac432013-07-10 11:19:26 -0700724 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
Adam Cohen53805212013-10-01 10:39:23 -0700725 if (am.isEnabled()) {
726 // Notify the user when the page changes
727 announceForAccessibility(getCurrentPageDescription());
Adam Cohen0ffac432013-07-10 11:19:26 -0700728 }
Michael Jurka0142d492010-08-25 17:46:15 -0700729 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700730 }
Michael Jurka0142d492010-08-25 17:46:15 -0700731 return false;
732 }
733
734 @Override
735 public void computeScroll() {
736 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700737 }
738
Adam Cohen7d30a372013-07-01 17:03:59 -0700739 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
740 return mTopAlignPageWhenShrinkingForBouncer;
741 }
742
Adam Cohen96d30a12013-07-16 18:13:21 -0700743 public static class LayoutParams extends ViewGroup.LayoutParams {
744 public boolean isFullScreenPage = false;
745
746 /**
747 * {@inheritDoc}
748 */
749 public LayoutParams(int width, int height) {
750 super(width, height);
751 }
752
753 public LayoutParams(ViewGroup.LayoutParams source) {
754 super(source);
755 }
756 }
757
758 protected LayoutParams generateDefaultLayoutParams() {
759 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
760 }
761
Adam Cohenedb40762013-07-18 16:45:45 -0700762 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700763 LayoutParams lp = generateDefaultLayoutParams();
764 lp.isFullScreenPage = true;
765 super.addView(page, 0, lp);
766 }
767
Adam Cohen410f3cd2013-09-22 12:09:32 -0700768 public int getNormalChildHeight() {
769 return mNormalChildHeight;
770 }
771
Winson Chung321e9ee2010-08-09 13:37:56 -0700772 @Override
773 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700774 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700775 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
776 return;
777 }
778
Adam Cohen7d30a372013-07-01 17:03:59 -0700779 // We measure the dimensions of the PagedView to be larger than the pages so that when we
780 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700781 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
782 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
783 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700784 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700785 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
786 // viewport, we can be at most one and a half screens offset once we scale down
787 DisplayMetrics dm = getResources().getDisplayMetrics();
Adam Cohendbdff6b2013-09-18 19:09:15 -0700788 int maxSize = Math.max(dm.widthPixels, dm.heightPixels + mInsets.top + mInsets.bottom);
Adam Cohen410f3cd2013-09-22 12:09:32 -0700789
Winson Chungc58497e2013-09-03 17:48:37 -0700790 int parentWidthSize, parentHeightSize;
791 int scaledWidthSize, scaledHeightSize;
792 if (mUseMinScale) {
793 parentWidthSize = (int) (1.5f * maxSize);
794 parentHeightSize = maxSize;
795 scaledWidthSize = (int) (parentWidthSize / mMinScale);
796 scaledHeightSize = (int) (parentHeightSize / mMinScale);
797 } else {
798 scaledWidthSize = widthSize;
799 scaledHeightSize = heightSize;
800 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700801 mViewport.set(0, 0, widthSize, heightSize);
802
803 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
804 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
805 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700806 }
807
Winson Chung8aad6102012-05-11 16:27:49 -0700808 // Return early if we aren't given a proper dimension
809 if (widthSize <= 0 || heightSize <= 0) {
810 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
811 return;
812 }
813
Adam Lesinski6b879f02010-11-04 16:15:23 -0700814 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
815 * of the All apps view on XLarge displays to not take up more space then it needs. Width
816 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
817 * each page to have the same width.
818 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700819 final int verticalPadding = getPaddingTop() + getPaddingBottom();
820 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700821
822 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700823 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700824 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700825 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
826 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
827 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
828 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700829 final int childCount = getChildCount();
830 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700831 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700832 final View child = getPageAt(i);
Vladimir Marko2824b072013-10-04 16:42:17 +0100833 if (child.getVisibility() != GONE) {
834 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700835
Vladimir Marko2824b072013-10-04 16:42:17 +0100836 int childWidthMode;
837 int childHeightMode;
838 int childWidth;
839 int childHeight;
Adam Cohen96d30a12013-07-16 18:13:21 -0700840
Vladimir Marko2824b072013-10-04 16:42:17 +0100841 if (!lp.isFullScreenPage) {
842 if (lp.width == LayoutParams.WRAP_CONTENT) {
843 childWidthMode = MeasureSpec.AT_MOST;
844 } else {
845 childWidthMode = MeasureSpec.EXACTLY;
846 }
847
848 if (lp.height == LayoutParams.WRAP_CONTENT) {
849 childHeightMode = MeasureSpec.AT_MOST;
850 } else {
851 childHeightMode = MeasureSpec.EXACTLY;
852 }
853
854 childWidth = widthSize - horizontalPadding;
855 childHeight = heightSize - verticalPadding - mInsets.top - mInsets.bottom;
856 mNormalChildHeight = childHeight;
857
Adam Cohen96d30a12013-07-16 18:13:21 -0700858 } else {
859 childWidthMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700860 childHeightMode = MeasureSpec.EXACTLY;
Vladimir Marko2824b072013-10-04 16:42:17 +0100861
862 if (mUseMinScale) {
863 childWidth = getViewportWidth();
864 childHeight = getViewportHeight();
865 } else {
866 childWidth = widthSize - getPaddingLeft() - getPaddingRight();
867 childHeight = heightSize - getPaddingTop() - getPaddingBottom();
868 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700869 }
870
Vladimir Marko2824b072013-10-04 16:42:17 +0100871 final int childWidthMeasureSpec =
872 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
873 final int childHeightMeasureSpec =
874 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
875 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700876 }
Adam Lesinski6b879f02010-11-04 16:15:23 -0700877 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700878 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700879
Winson Chunga128a7b2012-04-30 15:23:15 -0700880 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700881 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700882 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700883 // The gap between pages in the PagedView should be equal to the gap from the page
884 // to the edge of the screen (so it is not visible in the current screen). To
885 // account for unequal padding on each side of the paged view, we take the maximum
886 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700887 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700888 int spacing = Math.max(offset, widthSize - offset -
889 getChildAt(0).getMeasuredWidth());
890 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700891 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700892 }
893 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700894 }
895
Adam Cohen60b07122011-11-14 17:26:06 -0800896 public void setPageSpacing(int pageSpacing) {
897 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700898 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800899 }
900
Michael Jurkafe0ace32013-10-03 01:05:14 -0700901 protected int getFirstChildLeft() {
902 return mFirstChildLeft;
903 }
904
Winson Chung321e9ee2010-08-09 13:37:56 -0700905 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700906 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700907 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700908 return;
909 }
910
Winson Chung785d2eb2011-04-14 16:08:02 -0700911 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700912 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700913
Adam Cohenedb40762013-07-18 16:45:45 -0700914 int screenWidth = getViewportWidth();
915
Adam Cohen7d30a372013-07-01 17:03:59 -0700916 int offsetX = getViewportOffsetX();
917 int offsetY = getViewportOffsetY();
918
919 // Update the viewport offsets
920 mViewport.offset(offsetX, offsetY);
921
Adam Cohen0ffac432013-07-10 11:19:26 -0700922 final boolean isRtl = isLayoutRtl();
923
924 final int startIndex = isRtl ? childCount - 1 : 0;
925 final int endIndex = isRtl ? -1 : childCount;
926 final int delta = isRtl ? -1 : 1;
927
Adam Cohen7d30a372013-07-01 17:03:59 -0700928 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700929
Michael Jurkafe0ace32013-10-03 01:05:14 -0700930 int childLeft = mFirstChildLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700931 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
932 mPageScrolls = new int[getChildCount()];
933 }
934
Adam Cohen0ffac432013-07-10 11:19:26 -0700935 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen22f823d2011-09-01 17:22:18 -0700936 final View child = getPageAt(i);
Winson Chung321e9ee2010-08-09 13:37:56 -0700937 if (child.getVisibility() != View.GONE) {
Vladimir Marko2824b072013-10-04 16:42:17 +0100938 LayoutParams lp = (LayoutParams) child.getLayoutParams();
939 int childTop;
940 if (lp.isFullScreenPage) {
941 childTop = offsetY;
942 } else {
943 childTop = offsetY + getPaddingTop() + mInsets.top;
944 if (mCenterPagesVertically) {
945 childTop += (getViewportHeight() - mInsets.top - mInsets.bottom - verticalPadding - child.getMeasuredHeight()) / 2;
946 }
947 }
948
Adam Cohen96d30a12013-07-16 18:13:21 -0700949 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700950 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800951
Winson Chung785d2eb2011-04-14 16:08:02 -0700952 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700953 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800954 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700955
956 // We assume the left and right padding are equal, and hence center the pages
957 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700958 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700959 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
960
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700961 if (i != endIndex - delta) {
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700962 childLeft += childWidth + scrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700963 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
Adam Cohenaf9b0e52013-09-23 19:27:38 -0700964 childLeft += nextScrollOffset;
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700965 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700966 }
967 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700968
969 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
970 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800971 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700972 setHorizontalScrollBarEnabled(true);
973 mFirstLayout = false;
974 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700975
976 if (childCount > 0) {
977 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700978 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700979 } else {
980 mMaxScrollX = 0;
981 }
982
983 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
984 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700985 if (mRestorePage > -1) {
986 setCurrentPage(mRestorePage);
987 mRestorePage = -1;
988 } else {
989 setCurrentPage(getNextPage());
990 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700991 }
992 mChildCountOnLastLayout = getChildCount();
Adam Cohenf358a4b2013-07-23 16:47:31 -0700993
994 if (isReordering(true)) {
995 updateDragViewTranslationDuringDrag();
996 }
Winson Chunge3193b92010-09-10 11:44:42 -0700997 }
998
Adam Cohenf34bab52010-09-30 14:11:56 -0700999 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -07001000 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
1001
1002 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -07001003 for (int i = 0; i < getChildCount(); i++) {
1004 View child = getChildAt(i);
1005 if (child != null) {
1006 float scrollProgress = getScrollProgress(screenCenter, child, i);
1007 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -08001008 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -07001009 }
1010 }
1011 invalidate();
1012 }
Adam Cohenf34bab52010-09-30 14:11:56 -07001013 }
1014
Winson Chungc58497e2013-09-03 17:48:37 -07001015 protected void enablePagedViewAnimations() {
1016 mAllowPagedViewAnimations = true;
1017
1018 }
1019 protected void disablePagedViewAnimations() {
1020 mAllowPagedViewAnimations = false;
1021 }
1022
Winson Chunge3193b92010-09-10 11:44:42 -07001023 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -07001024 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -07001025 // Update the page indicator, we don't update the page indicator as we
1026 // add/remove pages
1027 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -07001028 int pageIndex = indexOfChild(child);
Winson Chung7819a562013-09-19 15:55:45 -07001029 mPageIndicator.addMarker(pageIndex,
1030 getPageIndicatorMarker(pageIndex),
Winson Chungc58497e2013-09-03 17:48:37 -07001031 mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001032 }
1033
Adam Cohen2591f6a2011-10-25 14:36:40 -07001034 // This ensures that when children are added, they get the correct transforms / alphas
1035 // in accordance with any scroll effects.
1036 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -07001037 mRecomputePageSpacing = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001038 updateFreescrollBounds();
Adam Cohen2591f6a2011-10-25 14:36:40 -07001039 invalidate();
1040 }
1041
Michael Jurka8b805b12012-04-18 14:23:14 -07001042 @Override
1043 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001044 mForceScreenScrolled = true;
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001045 updateFreescrollBounds();
Adam Cohen7d30a372013-07-01 17:03:59 -07001046 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -07001047 }
1048
Winson Chungd2be3812013-07-16 11:11:32 -07001049 private void removeMarkerForView(int index) {
1050 // Update the page indicator, we don't update the page indicator as we
1051 // add/remove pages
1052 if (mPageIndicator != null && !isReordering(false)) {
Winson Chungc58497e2013-09-03 17:48:37 -07001053 mPageIndicator.removeMarker(index, mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001054 }
1055 }
1056
1057 @Override
1058 public void removeView(View v) {
1059 // XXX: We should find a better way to hook into this before the view
1060 // gets removed form its parent...
1061 removeMarkerForView(indexOfChild(v));
1062 super.removeView(v);
1063 }
1064 @Override
1065 public void removeViewInLayout(View v) {
1066 // XXX: We should find a better way to hook into this before the view
1067 // gets removed form its parent...
1068 removeMarkerForView(indexOfChild(v));
1069 super.removeViewInLayout(v);
1070 }
1071 @Override
1072 public void removeViewAt(int index) {
1073 // XXX: We should find a better way to hook into this before the view
1074 // gets removed form its parent...
1075 removeViewAt(index);
1076 super.removeViewAt(index);
1077 }
1078 @Override
1079 public void removeAllViewsInLayout() {
1080 // Update the page indicator, we don't update the page indicator as we
1081 // add/remove pages
1082 if (mPageIndicator != null) {
Winson Chungc58497e2013-09-03 17:48:37 -07001083 mPageIndicator.removeAllMarkers(mAllowPagedViewAnimations);
Winson Chungd2be3812013-07-16 11:11:32 -07001084 }
1085
1086 super.removeAllViewsInLayout();
1087 }
1088
Adam Cohen73894962011-10-31 13:17:17 -07001089 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001090 if (index < 0 || index > getChildCount() - 1) return 0;
1091
Adam Cohenf698c6e2013-07-17 18:44:25 -07001092 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -07001093
Adam Cohenf698c6e2013-07-17 18:44:25 -07001094 return offset;
Adam Cohen73894962011-10-31 13:17:17 -07001095 }
1096
Adam Cohenf358a4b2013-07-23 16:47:31 -07001097 protected void getOverviewModePages(int[] range) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001098 range[0] = 0;
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001099 range[1] = Math.max(0, getChildCount() - 1);
Adam Cohen7d30a372013-07-01 17:03:59 -07001100 }
1101
Michael Jurkadde558b2011-11-09 22:09:06 -08001102 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001103 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001104 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001105
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001106 range[0] = -1;
1107 range[1] = -1;
1108
Michael Jurkac4fb9172010-09-02 17:19:20 -07001109 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001110 int viewportWidth = getViewportWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001111 int curScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001112
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001113 int count = getChildCount();
1114 for (int i = 0; i < count; i++) {
1115 View currPage = getPageAt(i);
Winson Chungc9ca2982013-07-19 12:07:38 -07001116
Winson Chungc9ca2982013-07-19 12:07:38 -07001117 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001118 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001119 if (mTmpIntPoint[0] > viewportWidth) {
1120 if (range[0] == -1) {
1121 continue;
1122 } else {
1123 break;
1124 }
1125 }
1126
Adam Cohen6a678da2013-09-24 10:58:01 -07001127 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001128 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1129 if (mTmpIntPoint[0] < 0) {
1130 if (range[0] == -1) {
1131 continue;
1132 } else {
1133 break;
1134 }
1135 }
1136 curScreen = i;
1137 if (range[0] < 0) {
1138 range[0] = curScreen;
Winson Chungc9ca2982013-07-19 12:07:38 -07001139 }
1140 }
Adam Cohenaf9b0e52013-09-23 19:27:38 -07001141
1142 range[1] = curScreen;
Michael Jurkadde558b2011-11-09 22:09:06 -08001143 } else {
1144 range[0] = -1;
1145 range[1] = -1;
1146 }
1147 }
1148
Michael Jurka920d7f42012-05-14 16:29:55 -07001149 protected boolean shouldDrawChild(View child) {
Adam Cohenf3434992013-09-16 16:52:59 -07001150 return child.getAlpha() > 0 && child.getVisibility() == VISIBLE;
Michael Jurka920d7f42012-05-14 16:29:55 -07001151 }
1152
Michael Jurkadde558b2011-11-09 22:09:06 -08001153 @Override
1154 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001155 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001156 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1157 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001158 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001159
1160 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001161 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1162 // set it for the next frame
1163 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001164 screenScrolled(screenCenter);
1165 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001166 }
1167
1168 // Find out which screens are visible; as an optimization we only call draw on them
1169 final int pageCount = getChildCount();
1170 if (pageCount > 0) {
1171 getVisiblePages(mTempVisiblePagesRange);
1172 final int leftScreen = mTempVisiblePagesRange[0];
1173 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001174 if (leftScreen != -1 && rightScreen != -1) {
1175 final long drawingTime = getDrawingTime();
1176 // Clip to the bounds
1177 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001178 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1179 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001180
Adam Cohen7d30a372013-07-01 17:03:59 -07001181 // Draw all the children, leaving the drag view for last
1182 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001183 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001184 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001185 if (mForceDrawAllChildrenNextFrame ||
1186 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001187 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001188 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001189 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001190 // Draw the drag view on top (if there is one)
1191 if (mDragView != null) {
1192 drawChild(canvas, mDragView, drawingTime);
1193 }
1194
Michael Jurka5e368ff2012-05-14 23:13:15 -07001195 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001196 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001197 }
Michael Jurka0142d492010-08-25 17:46:15 -07001198 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001199 }
1200
1201 @Override
1202 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001203 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001204 if (page != mCurrentPage || !mScroller.isFinished()) {
1205 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001206 return true;
1207 }
1208 return false;
1209 }
1210
1211 @Override
1212 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001213 int focusablePage;
1214 if (mNextPage != INVALID_PAGE) {
1215 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001216 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001217 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001218 }
Winson Chung86f77532010-08-24 11:08:22 -07001219 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001220 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001221 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001222 }
1223 return false;
1224 }
1225
1226 @Override
1227 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001228 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001229 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001230 if (getCurrentPage() > 0) {
1231 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001232 return true;
1233 }
1234 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001235 if (getCurrentPage() < getPageCount() - 1) {
1236 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001237 return true;
1238 }
1239 }
1240 return super.dispatchUnhandledMove(focused, direction);
1241 }
1242
1243 @Override
1244 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001245 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001246 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001247 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001248 }
1249 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001250 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001251 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001252 }
1253 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001254 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001255 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001256 }
1257 }
1258 }
1259
1260 /**
1261 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001262 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001263 *
Winson Chung86f77532010-08-24 11:08:22 -07001264 * This happens when live folders requery, and if they're off page, they
1265 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001266 */
1267 @Override
1268 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001269 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001270 View v = focused;
1271 while (true) {
1272 if (v == current) {
1273 super.focusableViewAvailable(focused);
1274 return;
1275 }
1276 if (v == this) {
1277 return;
1278 }
1279 ViewParent parent = v.getParent();
1280 if (parent instanceof View) {
1281 v = (View)v.getParent();
1282 } else {
1283 return;
1284 }
1285 }
1286 }
1287
1288 /**
1289 * {@inheritDoc}
1290 */
1291 @Override
1292 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1293 if (disallowIntercept) {
1294 // We need to make sure to cancel our long press if
1295 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001296 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001297 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001298 }
1299 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1300 }
1301
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001302 /**
1303 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1304 */
1305 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001306 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001307 if (isLayoutRtl()) {
1308 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001309 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001310 }
Adam Cohenedb40762013-07-18 16:45:45 -07001311 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001312 }
1313
1314 /**
1315 * Return true if a tap at (x, y) should trigger a flip to the next page.
1316 */
1317 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001318 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001319 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001320 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001321 }
1322 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001323 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001324 }
Winson Chung52aee602013-01-30 12:01:02 -08001325
Adam Cohen7d30a372013-07-01 17:03:59 -07001326 /** Returns whether x and y originated within the buffered viewport */
1327 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1328 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1329 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1330 return mTmpRect.contains(x, y);
1331 }
1332
Winson Chung321e9ee2010-08-09 13:37:56 -07001333 @Override
1334 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001335 if (DISABLE_TOUCH_INTERACTION) {
1336 return false;
1337 }
1338
Winson Chung321e9ee2010-08-09 13:37:56 -07001339 /*
1340 * This method JUST determines whether we want to intercept the motion.
1341 * If we return true, onTouchEvent will be called and we do the actual
1342 * scrolling there.
1343 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001344 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001345
Winson Chung45e1d6e2010-11-09 17:19:49 -08001346 // Skip touch handling if there are no pages to swipe
1347 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1348
Winson Chung321e9ee2010-08-09 13:37:56 -07001349 /*
1350 * Shortcut the most recurring case: the user is in the dragging
1351 * state and he is moving his finger. We want to intercept this
1352 * motion.
1353 */
1354 final int action = ev.getAction();
1355 if ((action == MotionEvent.ACTION_MOVE) &&
1356 (mTouchState == TOUCH_STATE_SCROLLING)) {
1357 return true;
1358 }
1359
Winson Chung321e9ee2010-08-09 13:37:56 -07001360 switch (action & MotionEvent.ACTION_MASK) {
1361 case MotionEvent.ACTION_MOVE: {
1362 /*
1363 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1364 * whether the user has moved far enough from his original down touch.
1365 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001366 if (mActivePointerId != INVALID_POINTER) {
1367 determineScrollingStart(ev);
Michael Jurka1ff706b2010-09-14 17:35:20 -07001368 }
1369 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1370 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1371 // i.e. fall through to the next case (don't break)
1372 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1373 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Adam Cohen93c97562013-09-26 13:48:01 -07001374 break;
Winson Chung321e9ee2010-08-09 13:37:56 -07001375 }
1376
1377 case MotionEvent.ACTION_DOWN: {
1378 final float x = ev.getX();
1379 final float y = ev.getY();
1380 // Remember location of down touch
1381 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001382 mDownMotionY = y;
1383 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001384 mLastMotionX = x;
1385 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001386 float[] p = mapPointFromViewToParent(this, x, y);
1387 mParentDownMotionX = p[0];
1388 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001389 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001390 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001391 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001392
Winson Chung321e9ee2010-08-09 13:37:56 -07001393 /*
1394 * If being flinged and user touches the screen, initiate drag;
1395 * otherwise don't. mScroller.isFinished should be false when
1396 * being flinged.
1397 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001398 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001399 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1400 if (finishedScrolling) {
1401 mTouchState = TOUCH_STATE_REST;
1402 mScroller.abortAnimation();
1403 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001404 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1405 mTouchState = TOUCH_STATE_SCROLLING;
1406 } else {
1407 mTouchState = TOUCH_STATE_REST;
1408 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001409 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001410
Winson Chung86f77532010-08-24 11:08:22 -07001411 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001412 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001413 if (!DISABLE_TOUCH_SIDE_PAGES) {
1414 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1415 if (getChildCount() > 0) {
1416 if (hitsPreviousPage(x, y)) {
1417 mTouchState = TOUCH_STATE_PREV_PAGE;
1418 } else if (hitsNextPage(x, y)) {
1419 mTouchState = TOUCH_STATE_NEXT_PAGE;
1420 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001421 }
1422 }
1423 }
1424 break;
1425 }
1426
Winson Chung321e9ee2010-08-09 13:37:56 -07001427 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001428 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001429 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001430 break;
1431
1432 case MotionEvent.ACTION_POINTER_UP:
1433 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001434 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001435 break;
1436 }
1437
1438 /*
1439 * The only time we want to intercept motion events is if we are in the
1440 * drag mode.
1441 */
1442 return mTouchState != TOUCH_STATE_REST;
1443 }
1444
Adam Cohenf8d28232011-02-01 21:47:00 -08001445 protected void determineScrollingStart(MotionEvent ev) {
1446 determineScrollingStart(ev, 1.0f);
1447 }
1448
Winson Chung321e9ee2010-08-09 13:37:56 -07001449 /*
1450 * Determines if we should change the touch state to start scrolling after the
1451 * user moves their touch point too far.
1452 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001453 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001454 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001455 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001456 if (pointerIndex == -1) return;
1457
1458 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001459 final float x = ev.getX(pointerIndex);
1460 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001461 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1462
Winson Chung321e9ee2010-08-09 13:37:56 -07001463 final int xDiff = (int) Math.abs(x - mLastMotionX);
1464 final int yDiff = (int) Math.abs(y - mLastMotionY);
1465
Adam Cohenf8d28232011-02-01 21:47:00 -08001466 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001467 boolean xPaged = xDiff > mPagingTouchSlop;
1468 boolean xMoved = xDiff > touchSlop;
1469 boolean yMoved = yDiff > touchSlop;
1470
Adam Cohenf8d28232011-02-01 21:47:00 -08001471 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001472 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001473 // Scroll if the user moved far enough along the X axis
1474 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001475 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001476 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001477 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001478 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001479 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1480 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001481 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001482 }
1483 }
1484
Adam Cohen7d30a372013-07-01 17:03:59 -07001485 protected float getMaxScrollProgress() {
1486 return 1.0f;
1487 }
1488
Adam Cohenf8d28232011-02-01 21:47:00 -08001489 protected void cancelCurrentPageLongPress() {
1490 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001491 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001492 // Try canceling the long press. It could also have been scheduled
1493 // by a distant descendant, so use the mAllowLongPress flag to block
1494 // everything
1495 final View currentPage = getPageAt(mCurrentPage);
1496 if (currentPage != null) {
1497 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001498 }
1499 }
1500 }
1501
Adam Cohen7d30a372013-07-01 17:03:59 -07001502 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1503 final int halfScreenSize = getViewportWidth() / 2;
1504
1505 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1506 screenCenter = Math.max(halfScreenSize, screenCenter);
1507
1508 return getScrollProgress(screenCenter, v, page);
1509 }
1510
Adam Cohenb5ba0972011-09-07 18:02:31 -07001511 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001512 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001513
Adam Cohen96d30a12013-07-16 18:13:21 -07001514 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001515 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001516
1517 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001518 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1519 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001520 return scrollProgress;
1521 }
1522
Adam Cohenedb40762013-07-18 16:45:45 -07001523 public int getScrollForPage(int index) {
Adam Cohen1f1f45d2013-10-02 09:40:18 -07001524 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
Adam Cohenedb40762013-07-18 16:45:45 -07001525 return 0;
1526 } else {
1527 return mPageScrolls[index];
1528 }
1529 }
1530
Adam Cohen564a2e72013-10-09 14:47:32 -07001531 // While layout transitions are occurring, a child's position may stray from its baseline
1532 // position. This method returns the magnitude of this stray at any given time.
1533 public int getLayoutTransitionOffsetForPage(int index) {
1534 if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) {
1535 return 0;
1536 } else {
1537 View child = getChildAt(index);
1538 int scrollOffset = (getViewportWidth() - child.getMeasuredWidth()) / 2;
1539 int baselineX = mPageScrolls[index] + scrollOffset + getViewportOffsetX();
1540 return (int) (child.getX() - baselineX);
1541 }
1542 }
1543
Adam Cohene0f66b52010-11-23 15:06:07 -08001544 // This curve determines how the effect of scrolling over the limits of the page dimishes
1545 // as the user pulls further and further from the bounds
1546 private float overScrollInfluenceCurve(float f) {
1547 f -= 1.0f;
1548 return f * f * f + 1.0f;
1549 }
1550
Adam Cohenb5ba0972011-09-07 18:02:31 -07001551 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001552 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001553
1554 // We want to reach the max over scroll effect when the user has
1555 // over scrolled half the size of the screen
1556 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1557
1558 if (f == 0) return;
1559
1560 // Clamp this factor, f, to -1 < f < 1
1561 if (Math.abs(f) >= 1) {
1562 f /= Math.abs(f);
1563 }
1564
1565 int overScrollAmount = (int) Math.round(f * screenSize);
1566 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001567 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001568 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001569 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001570 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001571 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001572 }
1573 invalidate();
1574 }
1575
1576 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001577 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001578
1579 float f = (amount / screenSize);
1580
1581 if (f == 0) return;
1582 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1583
Adam Cohen7bfc9792011-01-28 13:52:37 -08001584 // Clamp this factor, f, to -1 < f < 1
1585 if (Math.abs(f) >= 1) {
1586 f /= Math.abs(f);
1587 }
1588
Adam Cohene0f66b52010-11-23 15:06:07 -08001589 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001590 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001591 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001592 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001593 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001594 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001595 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001596 }
1597 invalidate();
1598 }
1599
Adam Cohenb5ba0972011-09-07 18:02:31 -07001600 protected void overScroll(float amount) {
1601 dampedOverScroll(amount);
1602 }
1603
Michael Jurkac5b262c2011-01-12 20:24:50 -08001604 protected float maxOverScroll() {
1605 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001606 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001607 float f = 1.0f;
1608 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1609 return OVERSCROLL_DAMP_FACTOR * f;
1610 }
1611
Adam Cohenf358a4b2013-07-23 16:47:31 -07001612 protected void enableFreeScroll() {
1613 setEnableFreeScroll(true, -1);
1614 }
1615
1616 protected void disableFreeScroll(int snapPage) {
1617 setEnableFreeScroll(false, snapPage);
1618 }
1619
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001620 void updateFreescrollBounds() {
1621 getOverviewModePages(mTempVisiblePagesRange);
1622 if (isLayoutRtl()) {
1623 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1624 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1625 } else {
1626 mFreeScrollMinScrollX = getScrollForPage(mTempVisiblePagesRange[0]);
1627 mFreeScrollMaxScrollX = getScrollForPage(mTempVisiblePagesRange[1]);
1628 }
1629 }
1630
Adam Cohenf358a4b2013-07-23 16:47:31 -07001631 private void setEnableFreeScroll(boolean freeScroll, int snapPage) {
1632 mFreeScroll = freeScroll;
1633
1634 if (snapPage == -1) {
1635 snapPage = getPageNearestToCenterOfScreen();
1636 }
1637
Adam Cohenf358a4b2013-07-23 16:47:31 -07001638 if (!mFreeScroll) {
1639 snapToPage(snapPage);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001640 } else {
Adam Cohen7a9e58a2013-10-01 18:02:13 -07001641 updateFreescrollBounds();
1642 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001643 if (getCurrentPage() < mTempVisiblePagesRange[0]) {
1644 setCurrentPage(mTempVisiblePagesRange[0]);
1645 } else if (getCurrentPage() > mTempVisiblePagesRange[1]) {
1646 setCurrentPage(mTempVisiblePagesRange[1]);
1647 }
1648 }
1649
1650 setEnableOverscroll(!freeScroll);
1651 }
1652
1653 private void setEnableOverscroll(boolean enable) {
1654 mAllowOverScroll = enable;
1655 }
1656
1657 int getNearestHoverOverPageIndex() {
1658 if (mDragView != null) {
1659 int dragX = (int) (mDragView.getLeft() + (mDragView.getMeasuredWidth() / 2)
1660 + mDragView.getTranslationX());
1661 getOverviewModePages(mTempVisiblePagesRange);
1662 int minDistance = Integer.MAX_VALUE;
1663 int minIndex = indexOfChild(mDragView);
1664 for (int i = mTempVisiblePagesRange[0]; i <= mTempVisiblePagesRange[1]; i++) {
1665 View page = getPageAt(i);
1666 int pageX = (int) (page.getLeft() + page.getMeasuredWidth() / 2);
1667 int d = Math.abs(dragX - pageX);
1668 if (d < minDistance) {
1669 minIndex = i;
1670 minDistance = d;
1671 }
1672 }
1673 return minIndex;
1674 }
1675 return -1;
1676 }
1677
Winson Chung321e9ee2010-08-09 13:37:56 -07001678 @Override
1679 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001680 if (DISABLE_TOUCH_INTERACTION) {
1681 return false;
1682 }
1683
Adam Cohen1697b792013-09-17 19:08:21 -07001684 super.onTouchEvent(ev);
1685
Winson Chung45e1d6e2010-11-09 17:19:49 -08001686 // Skip touch handling if there are no pages to swipe
1687 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1688
Michael Jurkab8f06722010-10-10 15:58:46 -07001689 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001690
1691 final int action = ev.getAction();
1692
1693 switch (action & MotionEvent.ACTION_MASK) {
1694 case MotionEvent.ACTION_DOWN:
1695 /*
1696 * If being flinged and user touches, stop the fling. isFinished
1697 * will be false if being flinged.
1698 */
1699 if (!mScroller.isFinished()) {
1700 mScroller.abortAnimation();
1701 }
1702
1703 // Remember where the motion event started
1704 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001705 mDownMotionY = mLastMotionY = ev.getY();
1706 mDownScrollX = getScrollX();
1707 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1708 mParentDownMotionX = p[0];
1709 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001710 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001711 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001712 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001713
Michael Jurka0142d492010-08-25 17:46:15 -07001714 if (mTouchState == TOUCH_STATE_SCROLLING) {
1715 pageBeginMoving();
1716 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001717 break;
1718
1719 case MotionEvent.ACTION_MOVE:
1720 if (mTouchState == TOUCH_STATE_SCROLLING) {
1721 // Scroll to follow the motion event
1722 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001723
1724 if (pointerIndex == -1) return true;
1725
Winson Chung321e9ee2010-08-09 13:37:56 -07001726 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001727 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001728
Adam Cohenaefd4e12011-02-14 16:39:38 -08001729 mTotalMotionX += Math.abs(deltaX);
1730
Winson Chungc0844aa2011-02-02 15:25:58 -08001731 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1732 // keep the remainder because we are actually testing if we've moved from the last
1733 // scrolled position (which is discrete).
1734 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001735 mTouchX += deltaX;
1736 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1737 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001738 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001739 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001740 } else {
1741 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001742 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001743 mLastMotionX = x;
1744 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001745 } else {
1746 awakenScrollBars();
1747 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001748 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1749 // Update the last motion position
1750 mLastMotionX = ev.getX();
1751 mLastMotionY = ev.getY();
1752
1753 // Update the parent down so that our zoom animations take this new movement into
1754 // account
1755 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1756 mParentDownMotionX = pt[0];
1757 mParentDownMotionY = pt[1];
1758 updateDragViewTranslationDuringDrag();
1759
1760 // Find the closest page to the touch point
1761 final int dragViewIndex = indexOfChild(mDragView);
Adam Cohen7d30a372013-07-01 17:03:59 -07001762
1763 // Change the drag view if we are hovering over the drop target
1764 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1765 (int) mParentDownMotionX, (int) mParentDownMotionY);
1766 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1767
Adam Cohen7d30a372013-07-01 17:03:59 -07001768 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1769 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1770 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1771 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1772
Adam Cohenf358a4b2013-07-23 16:47:31 -07001773 final int pageUnderPointIndex = getNearestHoverOverPageIndex();
1774 if (pageUnderPointIndex > -1 && pageUnderPointIndex != indexOfChild(mDragView) &&
1775 !isHoveringOverDelete) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001776 mTempVisiblePagesRange[0] = 0;
1777 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07001778 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001779 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1780 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1781 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1782 mSidePageHoverIndex = pageUnderPointIndex;
1783 mSidePageHoverRunnable = new Runnable() {
1784 @Override
1785 public void run() {
Adam Cohen7d30a372013-07-01 17:03:59 -07001786 // Setup the scroll to the correct page before we swap the views
1787 snapToPage(pageUnderPointIndex);
1788
1789 // For each of the pages between the paged view and the drag view,
1790 // animate them from the previous position to the new position in
1791 // the layout (as a result of the drag view moving in the layout)
1792 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1793 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1794 dragViewIndex + 1 : pageUnderPointIndex;
1795 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1796 dragViewIndex - 1 : pageUnderPointIndex;
1797 for (int i = lowerIndex; i <= upperIndex; ++i) {
1798 View v = getChildAt(i);
1799 // dragViewIndex < pageUnderPointIndex, so after we remove the
1800 // drag view all subsequent views to pageUnderPointIndex will
1801 // shift down.
1802 int oldX = getViewportOffsetX() + getChildOffset(i);
1803 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1804
1805 // Animate the view translation from its old position to its new
1806 // position
1807 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1808 if (anim != null) {
1809 anim.cancel();
1810 }
1811
1812 v.setTranslationX(oldX - newX);
1813 anim = new AnimatorSet();
1814 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1815 anim.playTogether(
1816 ObjectAnimator.ofFloat(v, "translationX", 0f));
1817 anim.start();
1818 v.setTag(anim);
1819 }
1820
1821 removeView(mDragView);
1822 onRemoveView(mDragView, false);
1823 addView(mDragView, pageUnderPointIndex);
1824 onAddView(mDragView, pageUnderPointIndex);
1825 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001826 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001827 }
1828 };
1829 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1830 }
1831 } else {
1832 removeCallbacks(mSidePageHoverRunnable);
1833 mSidePageHoverIndex = -1;
1834 }
Adam Cohen564976a2010-10-13 18:52:07 -07001835 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001836 determineScrollingStart(ev);
1837 }
1838 break;
1839
1840 case MotionEvent.ACTION_UP:
1841 if (mTouchState == TOUCH_STATE_SCROLLING) {
1842 final int activePointerId = mActivePointerId;
1843 final int pointerIndex = ev.findPointerIndex(activePointerId);
1844 final float x = ev.getX(pointerIndex);
1845 final VelocityTracker velocityTracker = mVelocityTracker;
1846 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1847 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001848 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001849 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001850 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1851 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001852
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001853 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1854
Adam Cohen00481b32011-11-18 12:03:48 -08001855 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001856 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001857
Adam Cohenf358a4b2013-07-23 16:47:31 -07001858 if (!mFreeScroll) {
1859 // In the case that the page is moved far to one direction and then is flung
1860 // in the opposite direction, we use a threshold to determine whether we should
1861 // just return to the starting page, or if we should skip one further.
1862 boolean returnToOriginalPage = false;
1863 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
1864 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
1865 returnToOriginalPage = true;
1866 }
Adam Cohenaefd4e12011-02-14 16:39:38 -08001867
Adam Cohenf358a4b2013-07-23 16:47:31 -07001868 int finalPage;
1869 // We give flings precedence over large moves, which is why we short-circuit our
1870 // test for a large move if a fling has been registered. That is, a large
1871 // move to the left and fling to the right will register as a fling to the right.
1872 final boolean isRtl = isLayoutRtl();
1873 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1874 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1875 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1876 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
1877 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1878 snapToPageWithVelocity(finalPage, velocityX);
1879 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1880 (isFling && isVelocityXLeft)) &&
1881 mCurrentPage < getChildCount() - 1) {
1882 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1883 snapToPageWithVelocity(finalPage, velocityX);
1884 } else {
1885 snapToDestination();
1886 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
1887 // at this point we have not moved beyond the touch slop
1888 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1889 // we can just page
1890 int nextPage = Math.max(0, mCurrentPage - 1);
1891 if (nextPage != mCurrentPage) {
1892 snapToPage(nextPage);
1893 } else {
1894 snapToDestination();
1895 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001896 } else {
Adam Cohenf358a4b2013-07-23 16:47:31 -07001897 if (!mScroller.isFinished()) {
1898 mScroller.abortAnimation();
1899 }
1900
1901 float scaleX = getScaleX();
1902 int vX = (int) (-velocityX * scaleX);
1903 int initialScrollX = (int) (getScrollX() * scaleX);
1904
1905 mScroller.fling(initialScrollX,
1906 getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
1907 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001908 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001909 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001910 // at this point we have not moved beyond the touch slop
1911 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1912 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001913 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1914 if (nextPage != mCurrentPage) {
1915 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001916 } else {
1917 snapToDestination();
1918 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001919 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1920 // Update the last motion position
1921 mLastMotionX = ev.getX();
1922 mLastMotionY = ev.getY();
1923
1924 // Update the parent down so that our zoom animations take this new movement into
1925 // account
1926 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1927 mParentDownMotionX = pt[0];
1928 mParentDownMotionY = pt[1];
1929 updateDragViewTranslationDuringDrag();
1930 boolean handledFling = false;
1931 if (!DISABLE_FLING_TO_DELETE) {
1932 // Check the velocity and see if we are flinging-to-delete
1933 PointF flingToDeleteVector = isFlingingToDelete();
1934 if (flingToDeleteVector != null) {
1935 onFlingToDelete(flingToDeleteVector);
1936 handledFling = true;
1937 }
1938 }
1939 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1940 (int) mParentDownMotionY)) {
1941 onDropToDelete();
1942 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001943 } else {
Adam Cohendbdff6b2013-09-18 19:09:15 -07001944 if (!mCancelTap) {
1945 onUnhandledTap(ev);
1946 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001947 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001948
1949 // Remove the callback to wait for the side page hover timeout
1950 removeCallbacks(mSidePageHoverRunnable);
1951 // End any intermediate reordering states
1952 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001953 break;
1954
1955 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001956 if (mTouchState == TOUCH_STATE_SCROLLING) {
1957 snapToDestination();
1958 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001959 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001960 break;
1961
1962 case MotionEvent.ACTION_POINTER_UP:
1963 onSecondaryPointerUp(ev);
Adam Cohenf358a4b2013-07-23 16:47:31 -07001964 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001965 break;
1966 }
1967
1968 return true;
1969 }
1970
Adam Cohen7d30a372013-07-01 17:03:59 -07001971 public void onFlingToDelete(View v) {}
1972 public void onRemoveView(View v, boolean deletePermanently) {}
1973 public void onRemoveViewAnimationCompleted() {}
1974 public void onAddView(View v, int index) {}
1975
1976 private void resetTouchState() {
1977 releaseVelocityTracker();
1978 endReordering();
Adam Cohendbdff6b2013-09-18 19:09:15 -07001979 mCancelTap = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07001980 mTouchState = TOUCH_STATE_REST;
1981 mActivePointerId = INVALID_POINTER;
Adam Cohen7d30a372013-07-01 17:03:59 -07001982 }
1983
Adam Cohen1697b792013-09-17 19:08:21 -07001984 protected void onUnhandledTap(MotionEvent ev) {
1985 ((Launcher) getContext()).onClick(this);
1986 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001987
Winson Chung185d7162011-02-28 13:47:29 -08001988 @Override
1989 public boolean onGenericMotionEvent(MotionEvent event) {
1990 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1991 switch (event.getAction()) {
1992 case MotionEvent.ACTION_SCROLL: {
1993 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1994 final float vscroll;
1995 final float hscroll;
1996 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1997 vscroll = 0;
1998 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1999 } else {
2000 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
2001 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
2002 }
2003 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07002004 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
2005 : (hscroll > 0 || vscroll > 0);
2006 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08002007 scrollRight();
2008 } else {
2009 scrollLeft();
2010 }
2011 return true;
2012 }
2013 }
2014 }
2015 }
2016 return super.onGenericMotionEvent(event);
2017 }
2018
Michael Jurkab8f06722010-10-10 15:58:46 -07002019 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
2020 if (mVelocityTracker == null) {
2021 mVelocityTracker = VelocityTracker.obtain();
2022 }
2023 mVelocityTracker.addMovement(ev);
2024 }
2025
2026 private void releaseVelocityTracker() {
2027 if (mVelocityTracker != null) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002028 mVelocityTracker.clear();
Michael Jurkab8f06722010-10-10 15:58:46 -07002029 mVelocityTracker.recycle();
2030 mVelocityTracker = null;
2031 }
2032 }
2033
Winson Chung321e9ee2010-08-09 13:37:56 -07002034 private void onSecondaryPointerUp(MotionEvent ev) {
2035 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
2036 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
2037 final int pointerId = ev.getPointerId(pointerIndex);
2038 if (pointerId == mActivePointerId) {
2039 // This was our active pointer going up. Choose a new
2040 // active pointer and adjust accordingly.
2041 // TODO: Make this decision more intelligent.
2042 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
2043 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
2044 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08002045 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07002046 mActivePointerId = ev.getPointerId(newPointerIndex);
2047 if (mVelocityTracker != null) {
2048 mVelocityTracker.clear();
2049 }
2050 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08002051 }
2052
Winson Chung321e9ee2010-08-09 13:37:56 -07002053 @Override
2054 public void requestChildFocus(View child, View focused) {
2055 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07002056 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07002057 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07002058 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07002059 }
2060 }
2061
Winson Chung1908d072011-02-24 18:09:44 -08002062 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07002063 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08002064 }
2065
Adam Cohen7d30a372013-07-01 17:03:59 -07002066 int getPageNearestToPoint(float x) {
2067 int index = 0;
2068 for (int i = 0; i < getChildCount(); ++i) {
2069 if (x < getChildAt(i).getRight() - getScrollX()) {
2070 return index;
2071 } else {
2072 index++;
2073 }
2074 }
2075 return Math.min(index, getChildCount() - 1);
2076 }
2077
Adam Cohend19d3ca2010-09-15 14:43:42 -07002078 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07002079 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07002080 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07002081 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07002082 final int childCount = getChildCount();
2083 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002084 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07002085 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07002086 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07002087 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07002088 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
2089 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
2090 minDistanceFromScreenCenter = distanceFromScreenCenter;
2091 minDistanceFromScreenCenterIndex = i;
2092 }
2093 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07002094 return minDistanceFromScreenCenterIndex;
2095 }
2096
2097 protected void snapToDestination() {
2098 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002099 }
2100
Adam Cohene0f66b52010-11-23 15:06:07 -08002101 private static class ScrollInterpolator implements Interpolator {
2102 public ScrollInterpolator() {
2103 }
2104
2105 public float getInterpolation(float t) {
2106 t -= 1.0f;
2107 return t*t*t*t*t + 1;
2108 }
2109 }
2110
2111 // We want the duration of the page snap animation to be influenced by the distance that
2112 // the screen has to travel, however, we don't want this duration to be effected in a
2113 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
2114 // of travel has on the overall snap duration.
2115 float distanceInfluenceForSnapDuration(float f) {
2116 f -= 0.5f; // center the values about 0.
2117 f *= 0.3f * Math.PI / 2.0f;
2118 return (float) Math.sin(f);
2119 }
2120
Michael Jurka0142d492010-08-25 17:46:15 -07002121 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002122 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07002123 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08002124
Adam Cohenedb40762013-07-18 16:45:45 -07002125 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08002126 int delta = newX - mUnboundedScrollX;
2127 int duration = 0;
2128
Adam Cohen265b9a62011-12-07 14:37:18 -08002129 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08002130 // If the velocity is low enough, then treat this more as an automatic page advance
2131 // as opposed to an apparent physical response to flinging
2132 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
2133 return;
2134 }
2135
2136 // Here we compute a "distance" that will be used in the computation of the overall
2137 // snap duration. This is a function of the actual distance that needs to be traveled;
2138 // we keep this value close to half screen size in order to reduce the variance in snap
2139 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07002140 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08002141 float distance = halfScreenSize + halfScreenSize *
2142 distanceInfluenceForSnapDuration(distanceRatio);
2143
2144 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08002145 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08002146
2147 // we want the page's snap velocity to approximately match the velocity at which the
2148 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07002149 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
2150 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08002151
2152 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07002153 }
2154
2155 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07002156 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07002157 }
2158
Adam Cohen7d30a372013-07-01 17:03:59 -07002159 protected void snapToPageImmediately(int whichPage) {
2160 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
2161 }
2162
Michael Jurka0142d492010-08-25 17:46:15 -07002163 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002164 snapToPage(whichPage, duration, false);
2165 }
2166
2167 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002168 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002169
Adam Cohenedb40762013-07-18 16:45:45 -07002170 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002171 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002172 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002173 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002174 }
2175
2176 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002177 snapToPage(whichPage, delta, duration, false);
2178 }
Michael Jurka0142d492010-08-25 17:46:15 -07002179
Adam Cohen7d30a372013-07-01 17:03:59 -07002180 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2181 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002182 View focusedChild = getFocusedChild();
2183 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002184 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002185 focusedChild.clearFocus();
2186 }
2187
Adam Cohen53805212013-10-01 10:39:23 -07002188 sendScrollAccessibilityEvent();
2189
Michael Jurka0142d492010-08-25 17:46:15 -07002190 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002191 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002192 if (immediate) {
2193 duration = 0;
2194 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002195 duration = Math.abs(delta);
2196 }
2197
Adam Cohenf358a4b2013-07-23 16:47:31 -07002198 if (!mScroller.isFinished()) {
2199 mScroller.abortAnimation();
2200 }
Adam Cohen68d73932010-11-15 10:50:58 -08002201 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002202
Michael Jurka0142d492010-08-25 17:46:15 -07002203 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002204
2205 // Trigger a compute() to finish switching pages if necessary
2206 if (immediate) {
2207 computeScroll();
2208 }
2209
Winson Chung9c0565f2013-07-19 13:49:06 -07002210 // Defer loading associated pages until the scroll settles
2211 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2212
Adam Cohen7d30a372013-07-01 17:03:59 -07002213 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002214 invalidate();
2215 }
2216
Winson Chung321e9ee2010-08-09 13:37:56 -07002217 public void scrollLeft() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002218 if (getNextPage() > 0) snapToPage(getNextPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002219 }
2220
2221 public void scrollRight() {
Adam Cohen2bf63d52013-09-29 17:46:49 -07002222 if (getNextPage() < getChildCount() -1) snapToPage(getNextPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002223 }
2224
Winson Chung86f77532010-08-24 11:08:22 -07002225 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002226 int result = -1;
2227 if (v != null) {
2228 ViewParent vp = v.getParent();
2229 int count = getChildCount();
2230 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002231 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002232 return i;
2233 }
2234 }
2235 }
2236 return result;
2237 }
2238
2239 /**
2240 * @return True is long presses are still allowed for the current touch
2241 */
2242 public boolean allowLongPress() {
2243 return mAllowLongPress;
2244 }
2245
Adam Cohendbdff6b2013-09-18 19:09:15 -07002246 @Override
2247 public boolean performLongClick() {
2248 mCancelTap = true;
2249 return super.performLongClick();
2250 }
2251
Michael Jurka0142d492010-08-25 17:46:15 -07002252 /**
2253 * Set true to allow long-press events to be triggered, usually checked by
2254 * {@link Launcher} to accept or block dpad-initiated long-presses.
2255 */
2256 public void setAllowLongPress(boolean allowLongPress) {
2257 mAllowLongPress = allowLongPress;
2258 }
2259
Winson Chung321e9ee2010-08-09 13:37:56 -07002260 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002261 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002262
2263 SavedState(Parcelable superState) {
2264 super(superState);
2265 }
2266
2267 private SavedState(Parcel in) {
2268 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002269 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002270 }
2271
2272 @Override
2273 public void writeToParcel(Parcel out, int flags) {
2274 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002275 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002276 }
2277
2278 public static final Parcelable.Creator<SavedState> CREATOR =
2279 new Parcelable.Creator<SavedState>() {
2280 public SavedState createFromParcel(Parcel in) {
2281 return new SavedState(in);
2282 }
2283
2284 public SavedState[] newArray(int size) {
2285 return new SavedState[size];
2286 }
2287 };
2288 }
2289
Winson Chungf314b0e2011-08-16 11:54:27 -07002290 protected void loadAssociatedPages(int page) {
2291 loadAssociatedPages(page, false);
2292 }
2293 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002294 if (mContentIsRefreshable) {
2295 final int count = getChildCount();
2296 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002297 int lowerPageBound = getAssociatedLowerPageBound(page);
2298 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002299 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2300 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002301 // First, clear any pages that should no longer be loaded
2302 for (int i = 0; i < count; ++i) {
2303 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002304 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002305 if (layout.getPageChildCount() > 0) {
2306 layout.removeAllViewsOnPage();
2307 }
2308 mDirtyPageContent.set(i, true);
2309 }
2310 }
2311 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002312 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002313 if ((i != page) && immediateAndOnly) {
2314 continue;
2315 }
Michael Jurka0142d492010-08-25 17:46:15 -07002316 if (lowerPageBound <= i && i <= upperPageBound) {
2317 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002318 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002319 mDirtyPageContent.set(i, false);
2320 }
Winson Chung86f77532010-08-24 11:08:22 -07002321 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002322 }
2323 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002324 }
2325 }
2326
Winson Chunge3193b92010-09-10 11:44:42 -07002327 protected int getAssociatedLowerPageBound(int page) {
2328 return Math.max(0, page - 1);
2329 }
2330 protected int getAssociatedUpperPageBound(int page) {
2331 final int count = getChildCount();
2332 return Math.min(page + 1, count - 1);
2333 }
2334
Winson Chung86f77532010-08-24 11:08:22 -07002335 /**
2336 * This method is called ONLY to synchronize the number of pages that the paged view has.
2337 * To actually fill the pages with information, implement syncPageItems() below. It is
2338 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2339 * and therefore, individual page items do not need to be updated in this method.
2340 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002341 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002342
2343 /**
2344 * This method is called to synchronize the items that are on a particular page. If views on
2345 * the page can be reused, then they should be updated within this method.
2346 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002347 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002348
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002349 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002350 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002351 }
2352 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002353 invalidatePageData(currentPage, false);
2354 }
2355 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002356 if (!mIsDataReady) {
2357 return;
2358 }
2359
Michael Jurka0142d492010-08-25 17:46:15 -07002360 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002361 // Force all scrolling-related behavior to end
2362 mScroller.forceFinished(true);
2363 mNextPage = INVALID_PAGE;
2364
Michael Jurka0142d492010-08-25 17:46:15 -07002365 // Update all the pages
2366 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002367
Winson Chung5a808352011-06-27 19:08:49 -07002368 // We must force a measure after we've loaded the pages to update the content width and
2369 // to determine the full scroll width
2370 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2371 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2372
2373 // Set a new page as the current page if necessary
2374 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002375 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002376 }
2377
Michael Jurka0142d492010-08-25 17:46:15 -07002378 // Mark each of the pages as dirty
2379 final int count = getChildCount();
2380 mDirtyPageContent.clear();
2381 for (int i = 0; i < count; ++i) {
2382 mDirtyPageContent.add(true);
2383 }
2384
2385 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002386 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002387 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002388 }
Adam Cohen06559042013-09-29 18:30:56 -07002389 if (isPageMoving()) {
2390 // If the page is moving, then snap it to the final position to ensure we don't get
2391 // stuck between pages
2392 snapToDestination();
2393 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002394 }
Winson Chung007c6982011-06-14 13:27:53 -07002395
Adam Cohen7d30a372013-07-01 17:03:59 -07002396 // Animate the drag view back to the original position
2397 void animateDragViewToOriginalPosition() {
2398 if (mDragView != null) {
2399 AnimatorSet anim = new AnimatorSet();
2400 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2401 anim.playTogether(
2402 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
Adam Cohenf358a4b2013-07-23 16:47:31 -07002403 ObjectAnimator.ofFloat(mDragView, "translationY", 0f),
2404 ObjectAnimator.ofFloat(mDragView, "scaleX", 1f),
2405 ObjectAnimator.ofFloat(mDragView, "scaleY", 1f));
Adam Cohen7d30a372013-07-01 17:03:59 -07002406 anim.addListener(new AnimatorListenerAdapter() {
2407 @Override
2408 public void onAnimationEnd(Animator animation) {
2409 onPostReorderingAnimationCompleted();
2410 }
2411 });
2412 anim.start();
2413 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002414 }
2415
Adam Cohen7d30a372013-07-01 17:03:59 -07002416 protected void onStartReordering() {
2417 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2418 mTouchState = TOUCH_STATE_REORDERING;
2419 mIsReordering = true;
2420
Adam Cohen7d30a372013-07-01 17:03:59 -07002421 // We must invalidate to trigger a redraw to update the layers such that the drag view
2422 // is always drawn on top
2423 invalidate();
2424 }
2425
2426 private void onPostReorderingAnimationCompleted() {
2427 // Trigger the callback when reordering has settled
2428 --mPostReorderingPreZoomInRemainingAnimationCount;
2429 if (mPostReorderingPreZoomInRunnable != null &&
2430 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2431 mPostReorderingPreZoomInRunnable.run();
2432 mPostReorderingPreZoomInRunnable = null;
2433 }
2434 }
2435
2436 protected void onEndReordering() {
2437 mIsReordering = false;
Adam Cohen7d30a372013-07-01 17:03:59 -07002438 }
2439
Adam Cohenf358a4b2013-07-23 16:47:31 -07002440 public boolean startReordering(View v) {
Adam Cohen93c97562013-09-26 13:48:01 -07002441 int dragViewIndex = indexOfChild(v);
2442
2443 if (mTouchState != TOUCH_STATE_REST) return false;
2444
Adam Cohen7d30a372013-07-01 17:03:59 -07002445 mTempVisiblePagesRange[0] = 0;
2446 mTempVisiblePagesRange[1] = getPageCount() - 1;
Adam Cohenf358a4b2013-07-23 16:47:31 -07002447 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002448 mReorderingStarted = true;
2449
2450 // Check if we are within the reordering range
2451 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
Adam Cohenf358a4b2013-07-23 16:47:31 -07002452 dragViewIndex <= mTempVisiblePagesRange[1]) {
2453 // Find the drag view under the pointer
2454 mDragView = getChildAt(dragViewIndex);
2455 mDragView.animate().scaleX(1.15f).scaleY(1.15f).setDuration(100).start();
2456 mDragViewBaselineLeft = mDragView.getLeft();
2457 disableFreeScroll(-1);
2458 onStartReordering();
Adam Cohen7d30a372013-07-01 17:03:59 -07002459 return true;
2460 }
2461 return false;
2462 }
2463
2464 boolean isReordering(boolean testTouchState) {
2465 boolean state = mIsReordering;
2466 if (testTouchState) {
2467 state &= (mTouchState == TOUCH_STATE_REORDERING);
2468 }
2469 return state;
2470 }
2471 void endReordering() {
2472 // For simplicity, we call endReordering sometimes even if reordering was never started.
2473 // In that case, we don't want to do anything.
2474 if (!mReorderingStarted) return;
2475 mReorderingStarted = false;
2476
2477 // If we haven't flung-to-delete the current child, then we just animate the drag view
2478 // back into position
2479 final Runnable onCompleteRunnable = new Runnable() {
2480 @Override
2481 public void run() {
2482 onEndReordering();
2483 }
2484 };
2485 if (!mDeferringForDelete) {
2486 mPostReorderingPreZoomInRunnable = new Runnable() {
2487 public void run() {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002488 onCompleteRunnable.run();
2489 enableFreeScroll();
Adam Cohen7d30a372013-07-01 17:03:59 -07002490 };
2491 };
2492
2493 mPostReorderingPreZoomInRemainingAnimationCount =
2494 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2495 // Snap to the current page
2496 snapToPage(indexOfChild(mDragView), 0);
2497 // Animate the drag view back to the front position
2498 animateDragViewToOriginalPosition();
2499 } else {
2500 // Handled in post-delete-animation-callbacks
2501 }
2502 }
2503
Adam Cohen7d30a372013-07-01 17:03:59 -07002504 /*
2505 * Flinging to delete - IN PROGRESS
2506 */
2507 private PointF isFlingingToDelete() {
2508 ViewConfiguration config = ViewConfiguration.get(getContext());
2509 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2510
2511 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2512 // Do a quick dot product test to ensure that we are flinging upwards
2513 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2514 mVelocityTracker.getYVelocity());
2515 PointF upVec = new PointF(0f, -1f);
2516 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2517 (vel.length() * upVec.length()));
2518 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2519 return vel;
2520 }
2521 }
2522 return null;
2523 }
2524
2525 /**
2526 * Creates an animation from the current drag view along its current velocity vector.
2527 * For this animation, the alpha runs for a fixed duration and we update the position
2528 * progressively.
2529 */
2530 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2531 private View mDragView;
2532 private PointF mVelocity;
2533 private Rect mFrom;
2534 private long mPrevTime;
2535 private float mFriction;
2536
2537 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2538
2539 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2540 long startTime, float friction) {
2541 mDragView = dragView;
2542 mVelocity = vel;
2543 mFrom = from;
2544 mPrevTime = startTime;
2545 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2546 }
2547
2548 @Override
2549 public void onAnimationUpdate(ValueAnimator animation) {
2550 float t = ((Float) animation.getAnimatedValue()).floatValue();
2551 long curTime = AnimationUtils.currentAnimationTimeMillis();
2552
2553 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2554 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2555
2556 mDragView.setTranslationX(mFrom.left);
2557 mDragView.setTranslationY(mFrom.top);
2558 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2559
2560 mVelocity.x *= mFriction;
2561 mVelocity.y *= mFriction;
2562 mPrevTime = curTime;
2563 }
2564 };
2565
2566 private static final int ANIM_TAG_KEY = 100;
2567
2568 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2569 return new Runnable() {
2570 @Override
2571 public void run() {
2572 int dragViewIndex = indexOfChild(dragView);
2573
2574 // For each of the pages around the drag view, animate them from the previous
2575 // position to the new position in the layout (as a result of the drag view moving
2576 // in the layout)
2577 // NOTE: We can make an assumption here because we have side-bound pages that we
2578 // will always have pages to animate in from the left
Adam Cohenf358a4b2013-07-23 16:47:31 -07002579 getOverviewModePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002580 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2581 boolean slideFromLeft = (isLastWidgetPage ||
2582 dragViewIndex > mTempVisiblePagesRange[0]);
2583
2584 // Setup the scroll to the correct page before we swap the views
2585 if (slideFromLeft) {
2586 snapToPageImmediately(dragViewIndex - 1);
2587 }
2588
2589 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2590 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2591 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2592 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2593 ArrayList<Animator> animations = new ArrayList<Animator>();
2594 for (int i = lowerIndex; i <= upperIndex; ++i) {
2595 View v = getChildAt(i);
2596 // dragViewIndex < pageUnderPointIndex, so after we remove the
2597 // drag view all subsequent views to pageUnderPointIndex will
2598 // shift down.
2599 int oldX = 0;
2600 int newX = 0;
2601 if (slideFromLeft) {
2602 if (i == 0) {
2603 // Simulate the page being offscreen with the page spacing
2604 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2605 - mPageSpacing;
2606 } else {
2607 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2608 }
2609 newX = getViewportOffsetX() + getChildOffset(i);
2610 } else {
2611 oldX = getChildOffset(i) - getChildOffset(i - 1);
2612 newX = 0;
2613 }
2614
2615 // Animate the view translation from its old position to its new
2616 // position
2617 AnimatorSet anim = (AnimatorSet) v.getTag();
2618 if (anim != null) {
2619 anim.cancel();
2620 }
2621
2622 // Note: Hacky, but we want to skip any optimizations to not draw completely
2623 // hidden views
2624 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2625 v.setTranslationX(oldX - newX);
2626 anim = new AnimatorSet();
2627 anim.playTogether(
2628 ObjectAnimator.ofFloat(v, "translationX", 0f),
2629 ObjectAnimator.ofFloat(v, "alpha", 1f));
2630 animations.add(anim);
2631 v.setTag(ANIM_TAG_KEY, anim);
2632 }
2633
2634 AnimatorSet slideAnimations = new AnimatorSet();
2635 slideAnimations.playTogether(animations);
2636 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2637 slideAnimations.addListener(new AnimatorListenerAdapter() {
2638 @Override
2639 public void onAnimationEnd(Animator animation) {
Adam Cohenf358a4b2013-07-23 16:47:31 -07002640 mDeferringForDelete = false;
2641 onEndReordering();
2642 onRemoveViewAnimationCompleted();
Adam Cohen7d30a372013-07-01 17:03:59 -07002643 }
2644 });
2645 slideAnimations.start();
2646
2647 removeView(dragView);
2648 onRemoveView(dragView, true);
2649 }
2650 };
2651 }
2652
2653 public void onFlingToDelete(PointF vel) {
2654 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2655
2656 // NOTE: Because it takes time for the first frame of animation to actually be
2657 // called and we expect the animation to be a continuation of the fling, we have
2658 // to account for the time that has elapsed since the fling finished. And since
2659 // we don't have a startDelay, we will always get call to update when we call
2660 // start() (which we want to ignore).
2661 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2662 private int mCount = -1;
2663 private long mStartTime;
2664 private float mOffset;
2665 /* Anonymous inner class ctor */ {
2666 mStartTime = startTime;
2667 }
2668
2669 @Override
2670 public float getInterpolation(float t) {
2671 if (mCount < 0) {
2672 mCount++;
2673 } else if (mCount == 0) {
2674 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2675 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2676 mCount++;
2677 }
2678 return Math.min(1f, mOffset + t);
2679 }
2680 };
2681
2682 final Rect from = new Rect();
2683 final View dragView = mDragView;
2684 from.left = (int) dragView.getTranslationX();
2685 from.top = (int) dragView.getTranslationY();
2686 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2687 from, startTime, FLING_TO_DELETE_FRICTION);
2688
2689 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2690
2691 // Create and start the animation
2692 ValueAnimator mDropAnim = new ValueAnimator();
2693 mDropAnim.setInterpolator(tInterpolator);
2694 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2695 mDropAnim.setFloatValues(0f, 1f);
2696 mDropAnim.addUpdateListener(updateCb);
2697 mDropAnim.addListener(new AnimatorListenerAdapter() {
2698 public void onAnimationEnd(Animator animation) {
2699 onAnimationEndRunnable.run();
2700 }
2701 });
2702 mDropAnim.start();
2703 mDeferringForDelete = true;
2704 }
2705
2706 /* Drag to delete */
2707 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2708 if (mDeleteDropTarget != null) {
2709 mAltTmpRect.set(0, 0, 0, 0);
2710 View parent = (View) mDeleteDropTarget.getParent();
2711 if (parent != null) {
2712 parent.getGlobalVisibleRect(mAltTmpRect);
2713 }
2714 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2715 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2716 return mTmpRect.contains(x, y);
2717 }
2718 return false;
2719 }
2720
2721 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2722
2723 private void onDropToDelete() {
2724 final View dragView = mDragView;
2725
2726 final float toScale = 0f;
2727 final float toAlpha = 0f;
2728
2729 // Create and start the complex animation
2730 ArrayList<Animator> animations = new ArrayList<Animator>();
2731 AnimatorSet motionAnim = new AnimatorSet();
2732 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2733 motionAnim.playTogether(
2734 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2735 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2736 animations.add(motionAnim);
2737
2738 AnimatorSet alphaAnim = new AnimatorSet();
2739 alphaAnim.setInterpolator(new LinearInterpolator());
2740 alphaAnim.playTogether(
2741 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2742 animations.add(alphaAnim);
2743
2744 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2745
2746 AnimatorSet anim = new AnimatorSet();
2747 anim.playTogether(animations);
2748 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2749 anim.addListener(new AnimatorListenerAdapter() {
2750 public void onAnimationEnd(Animator animation) {
2751 onAnimationEndRunnable.run();
2752 }
2753 });
2754 anim.start();
2755
2756 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002757 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002758
2759 /* Accessibility */
2760 @Override
2761 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2762 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002763 info.setScrollable(getPageCount() > 1);
2764 if (getCurrentPage() < getPageCount() - 1) {
2765 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2766 }
2767 if (getCurrentPage() > 0) {
2768 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2769 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002770 }
2771
2772 @Override
Alan Viverette254139a2013-10-08 13:13:46 -07002773 public void sendAccessibilityEvent(int eventType) {
2774 // Don't let the view send real scroll events.
2775 if (eventType != AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2776 super.sendAccessibilityEvent(eventType);
2777 }
2778 }
2779
2780 @Override
Winson Chung6a0f57d2011-06-29 20:10:49 -07002781 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2782 super.onInitializeAccessibilityEvent(event);
2783 event.setScrollable(true);
Winson Chung6a0f57d2011-06-29 20:10:49 -07002784 }
2785
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002786 @Override
2787 public boolean performAccessibilityAction(int action, Bundle arguments) {
2788 if (super.performAccessibilityAction(action, arguments)) {
2789 return true;
2790 }
2791 switch (action) {
2792 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2793 if (getCurrentPage() < getPageCount() - 1) {
2794 scrollRight();
2795 return true;
2796 }
2797 } break;
2798 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2799 if (getCurrentPage() > 0) {
2800 scrollLeft();
2801 return true;
2802 }
2803 } break;
2804 }
2805 return false;
2806 }
2807
Adam Cohen0ffac432013-07-10 11:19:26 -07002808 protected String getCurrentPageDescription() {
2809 return String.format(getContext().getString(R.string.default_scroll_format),
2810 getNextPage() + 1, getChildCount());
2811 }
2812
Winson Chungd11265e2011-08-30 13:37:23 -07002813 @Override
2814 public boolean onHoverEvent(android.view.MotionEvent event) {
2815 return true;
2816 }
Adam Cohen5084cba2013-09-03 12:01:16 -07002817}