blob: bb596a79ee282a382b0a65c15c071d140c6e8d79 [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 Cohen7d30a372013-07-01 17:03:59 -070027import android.content.res.Resources;
Adam Cohen9c4949e2010-10-05 12:27:22 -070028import android.content.res.TypedArray;
Winson Chung321e9ee2010-08-09 13:37:56 -070029import android.graphics.Canvas;
Adam Cohen7d30a372013-07-01 17:03:59 -070030import android.graphics.Matrix;
31import android.graphics.PointF;
Winson Chung321e9ee2010-08-09 13:37:56 -070032import android.graphics.Rect;
Svetoslav Ganov08055f62012-05-15 11:06:36 -070033import android.os.Bundle;
Winson Chung321e9ee2010-08-09 13:37:56 -070034import android.os.Parcel;
35import android.os.Parcelable;
36import 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;
Adam Cohen96d30a12013-07-16 18:13:21 -070047import android.view.ViewGroup.LayoutParams;
Winson Chung6a0f57d2011-06-29 20:10:49 -070048import android.view.accessibility.AccessibilityEvent;
Winson Chungc27d1bb2011-09-29 12:07:42 -070049import android.view.accessibility.AccessibilityManager;
Winson Chung6a0f57d2011-06-29 20:10:49 -070050import android.view.accessibility.AccessibilityNodeInfo;
Adam Cohen7d30a372013-07-01 17:03:59 -070051import android.view.animation.AnimationUtils;
52import android.view.animation.DecelerateInterpolator;
Adam Cohene0f66b52010-11-23 15:06:07 -080053import android.view.animation.Interpolator;
Adam Cohen7d30a372013-07-01 17:03:59 -070054import android.view.animation.LinearInterpolator;
Adam Cohen96d30a12013-07-16 18:13:21 -070055import android.widget.FrameLayout;
Winson Chung321e9ee2010-08-09 13:37:56 -070056import android.widget.Scroller;
57
Winson Chung6a0f57d2011-06-29 20:10:49 -070058import java.util.ArrayList;
59
Winson Chung321e9ee2010-08-09 13:37:56 -070060/**
61 * An abstraction of the original Workspace which supports browsing through a
Michael Jurka0142d492010-08-25 17:46:15 -070062 * sequential list of "pages"
Winson Chung321e9ee2010-08-09 13:37:56 -070063 */
Michael Jurka8b805b12012-04-18 14:23:14 -070064public abstract class PagedView extends ViewGroup implements ViewGroup.OnHierarchyChangeListener {
Winson Chung321e9ee2010-08-09 13:37:56 -070065 private static final String TAG = "PagedView";
Winson Chung785d2eb2011-04-14 16:08:02 -070066 private static final boolean DEBUG = false;
Michael Jurka0142d492010-08-25 17:46:15 -070067 protected static final int INVALID_PAGE = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -070068
Winson Chung86f77532010-08-24 11:08:22 -070069 // the min drag distance for a fling to register, to prevent random page shifts
Winson Chung9cfd25f2010-10-24 16:09:28 -070070 private static final int MIN_LENGTH_FOR_FLING = 25;
Winson Chung321e9ee2010-08-09 13:37:56 -070071
Adam Cohen7d30a372013-07-01 17:03:59 -070072 protected static final int PAGE_SNAP_ANIMATION_DURATION = 750;
Winson Chungf0c6ae02012-03-21 16:10:31 -070073 protected static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950;
Michael Jurka0142d492010-08-25 17:46:15 -070074 protected static final float NANOTIME_DIV = 1000000000.0f;
Winson Chung321e9ee2010-08-09 13:37:56 -070075
Adam Cohenb5ba0972011-09-07 18:02:31 -070076 private static final float OVERSCROLL_ACCELERATE_FACTOR = 2;
Winson Chungb26f3d62011-06-02 10:49:29 -070077 private static final float OVERSCROLL_DAMP_FACTOR = 0.14f;
Winson Chung867ca622012-02-21 15:48:35 -080078
Adam Cohenb64cb5a2011-02-15 13:53:42 -080079 private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f;
Adam Cohen00481b32011-11-18 12:03:48 -080080 // The page is moved more than halfway, automatically move to the next page on touch up.
81 private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f;
Adam Cohen68d73932010-11-15 10:50:58 -080082
Adam Cohen265b9a62011-12-07 14:37:18 -080083 // The following constants need to be scaled based on density. The scaled versions will be
84 // assigned to the corresponding member variables below.
85 private static final int FLING_THRESHOLD_VELOCITY = 500;
86 private static final int MIN_SNAP_VELOCITY = 1500;
87 private static final int MIN_FLING_VELOCITY = 250;
88
Adam Cohen7d30a372013-07-01 17:03:59 -070089 // We are disabling touch interaction of the widget region for factory ROM.
90 private static final boolean DISABLE_TOUCH_INTERACTION = false;
91 private static final boolean DISABLE_TOUCH_SIDE_PAGES = false;
Adam Cohendedbd962013-07-11 14:21:49 -070092 private static final boolean DISABLE_FLING_TO_DELETE = true;
Adam Cohen7d30a372013-07-01 17:03:59 -070093
Winson Chung8aad6102012-05-11 16:27:49 -070094 static final int AUTOMATIC_PAGE_SPACING = -1;
95
Adam Cohen265b9a62011-12-07 14:37:18 -080096 protected int mFlingThresholdVelocity;
97 protected int mMinFlingVelocity;
98 protected int mMinSnapVelocity;
Michael Jurka0142d492010-08-25 17:46:15 -070099
Adam Cohenb5ba0972011-09-07 18:02:31 -0700100 protected float mDensity;
Michael Jurka0142d492010-08-25 17:46:15 -0700101 protected float mSmoothingTime;
102 protected float mTouchX;
103
104 protected boolean mFirstLayout = true;
105
106 protected int mCurrentPage;
Winson Chung8c87cd82013-07-23 16:20:10 -0700107 protected int mRestorePage = -1;
Adam Cohenf698c6e2013-07-17 18:44:25 -0700108 protected int mChildCountOnLastLayout;
Adam Cohene61a9a22013-06-11 15:45:31 -0700109
Michael Jurka0142d492010-08-25 17:46:15 -0700110 protected int mNextPage = INVALID_PAGE;
Adam Cohen68d73932010-11-15 10:50:58 -0800111 protected int mMaxScrollX;
Michael Jurka0142d492010-08-25 17:46:15 -0700112 protected Scroller mScroller;
Winson Chung321e9ee2010-08-09 13:37:56 -0700113 private VelocityTracker mVelocityTracker;
114
Adam Cohen7d30a372013-07-01 17:03:59 -0700115 private float mParentDownMotionX;
116 private float mParentDownMotionY;
Winson Chung321e9ee2010-08-09 13:37:56 -0700117 private float mDownMotionX;
Adam Cohen7d30a372013-07-01 17:03:59 -0700118 private float mDownMotionY;
119 private float mDownScrollX;
Michael Jurka7426c422010-11-11 15:23:47 -0800120 protected float mLastMotionX;
Winson Chungc0844aa2011-02-02 15:25:58 -0800121 protected float mLastMotionXRemainder;
Michael Jurka7426c422010-11-11 15:23:47 -0800122 protected float mLastMotionY;
Adam Cohenaefd4e12011-02-14 16:39:38 -0800123 protected float mTotalMotionX;
Adam Cohenf34bab52010-09-30 14:11:56 -0700124 private int mLastScreenCenter = -1;
Adam Cohenedb40762013-07-18 16:45:45 -0700125
126 private int[] mPageScrolls;
Winson Chung321e9ee2010-08-09 13:37:56 -0700127
Michael Jurka0142d492010-08-25 17:46:15 -0700128 protected final static int TOUCH_STATE_REST = 0;
129 protected final static int TOUCH_STATE_SCROLLING = 1;
130 protected final static int TOUCH_STATE_PREV_PAGE = 2;
131 protected final static int TOUCH_STATE_NEXT_PAGE = 3;
Adam Cohen7d30a372013-07-01 17:03:59 -0700132 protected final static int TOUCH_STATE_REORDERING = 4;
133
Adam Cohene45440e2010-10-14 18:33:38 -0700134 protected final static float ALPHA_QUANTIZE_LEVEL = 0.0001f;
Winson Chung321e9ee2010-08-09 13:37:56 -0700135
Michael Jurka0142d492010-08-25 17:46:15 -0700136 protected int mTouchState = TOUCH_STATE_REST;
Adam Cohen2591f6a2011-10-25 14:36:40 -0700137 protected boolean mForceScreenScrolled = false;
Winson Chung321e9ee2010-08-09 13:37:56 -0700138
Michael Jurka0142d492010-08-25 17:46:15 -0700139 protected OnLongClickListener mLongClickListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700140
Michael Jurka7426c422010-11-11 15:23:47 -0800141 protected int mTouchSlop;
Winson Chung321e9ee2010-08-09 13:37:56 -0700142 private int mPagingTouchSlop;
143 private int mMaximumVelocity;
Adam Cohen9c4949e2010-10-05 12:27:22 -0700144 protected int mPageSpacing;
145 protected int mPageLayoutPaddingTop;
146 protected int mPageLayoutPaddingBottom;
147 protected int mPageLayoutPaddingLeft;
148 protected int mPageLayoutPaddingRight;
Winson Chungdf4b83d2010-10-20 17:49:27 -0700149 protected int mPageLayoutWidthGap;
150 protected int mPageLayoutHeightGap;
Michael Jurka87b14902011-05-25 22:13:09 -0700151 protected int mCellCountX = 0;
152 protected int mCellCountY = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700153 protected boolean mCenterPagesVertically;
Adam Cohen68d73932010-11-15 10:50:58 -0800154 protected boolean mAllowOverScroll = true;
155 protected int mUnboundedScrollX;
Michael Jurkadde558b2011-11-09 22:09:06 -0800156 protected int[] mTempVisiblePagesRange = new int[2];
Michael Jurka5e368ff2012-05-14 23:13:15 -0700157 protected boolean mForceDrawAllChildrenNextFrame;
Winson Chung321e9ee2010-08-09 13:37:56 -0700158
Michael Jurka8b805b12012-04-18 14:23:14 -0700159 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise
Adam Cohenebea84d2011-11-09 17:20:41 -0800160 // it is equal to the scaled overscroll position. We use a separate value so as to prevent
161 // the screens from continuing to translate beyond the normal bounds.
162 protected int mOverScrollX;
163
Michael Jurka5f1c5092010-09-03 14:15:02 -0700164 protected static final int INVALID_POINTER = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -0700165
Michael Jurka5f1c5092010-09-03 14:15:02 -0700166 protected int mActivePointerId = INVALID_POINTER;
Winson Chung321e9ee2010-08-09 13:37:56 -0700167
Winson Chung86f77532010-08-24 11:08:22 -0700168 private PageSwitchListener mPageSwitchListener;
Winson Chung321e9ee2010-08-09 13:37:56 -0700169
Michael Jurkae326f182011-11-21 14:05:46 -0800170 protected ArrayList<Boolean> mDirtyPageContent;
Winson Chung321e9ee2010-08-09 13:37:56 -0700171
Michael Jurka0142d492010-08-25 17:46:15 -0700172 // If true, syncPages and syncPageItems will be called to refresh pages
173 protected boolean mContentIsRefreshable = true;
174
175 // If true, modify alpha of neighboring pages as user scrolls left/right
Adam Cohen7d30a372013-07-01 17:03:59 -0700176 protected boolean mFadeInAdjacentScreens = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700177
178 // It true, use a different slop parameter (pagingTouchSlop = 2 * touchSlop) for deciding
179 // to switch to a new page
180 protected boolean mUsePagingTouchSlop = true;
181
Michael Jurka8b805b12012-04-18 14:23:14 -0700182 // If true, the subclass should directly update scrollX itself in its computeScroll method
Michael Jurka0142d492010-08-25 17:46:15 -0700183 // (SmoothPagedView does this)
184 protected boolean mDeferScrollUpdate = false;
Winson Chung9c0565f2013-07-19 13:49:06 -0700185 protected boolean mDeferLoadAssociatedPagesUntilScrollCompletes = false;
Michael Jurka0142d492010-08-25 17:46:15 -0700186
Patrick Dubroy1262e362010-10-06 15:49:50 -0700187 protected boolean mIsPageMoving = false;
188
Winson Chungf0ea4d32011-06-06 14:27:16 -0700189 // All syncs and layout passes are deferred until data is ready.
190 protected boolean mIsDataReady = false;
191
Adam Cohen7d30a372013-07-01 17:03:59 -0700192 protected boolean mAllowLongPress = true;
193
Winson Chungd2be3812013-07-16 11:11:32 -0700194 // Page Indicator
195 private int mPageIndicatorViewId;
196 private PageIndicator mPageIndicator;
Winson Chung007c6982011-06-14 13:27:53 -0700197
Adam Cohen7d30a372013-07-01 17:03:59 -0700198 // The viewport whether the pages are to be contained (the actual view may be larger than the
199 // viewport)
200 private Rect mViewport = new Rect();
201
202 // Reordering
203 // We use the min scale to determine how much to expand the actually PagedView measured
204 // dimensions such that when we are zoomed out, the view is not clipped
205 private int REORDERING_DROP_REPOSITION_DURATION = 200;
206 protected int REORDERING_REORDER_REPOSITION_DURATION = 300;
207 protected int REORDERING_ZOOM_IN_OUT_DURATION = 250;
208 private int REORDERING_SIDE_PAGE_HOVER_TIMEOUT = 300;
209 private float REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE = 0.1f;
210 private long REORDERING_DELETE_DROP_TARGET_FADE_DURATION = 150;
211 private float mMinScale = 1f;
212 protected View mDragView;
213 protected AnimatorSet mZoomInOutAnim;
214 private Runnable mSidePageHoverRunnable;
215 private int mSidePageHoverIndex = -1;
216 // This variable's scope is only for the duration of startReordering() and endReordering()
217 private boolean mReorderingStarted = false;
218 // This variable's scope is for the duration of startReordering() and after the zoomIn()
219 // animation after endReordering()
220 private boolean mIsReordering;
221 // The runnable that settles the page after snapToPage and animateDragViewToOriginalPosition
222 private int NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT = 2;
223 private int mPostReorderingPreZoomInRemainingAnimationCount;
224 private Runnable mPostReorderingPreZoomInRunnable;
225
226 // Edge swiping
227 private boolean mOnlyAllowEdgeSwipes = false;
228 private boolean mDownEventOnEdge = false;
229 private int mEdgeSwipeRegionSize = 0;
230
231 // Convenience/caching
232 private Matrix mTmpInvMatrix = new Matrix();
233 private float[] mTmpPoint = new float[2];
Winson Chungc9ca2982013-07-19 12:07:38 -0700234 private int[] mTmpIntPoint = new int[2];
Adam Cohen7d30a372013-07-01 17:03:59 -0700235 private Rect mTmpRect = new Rect();
236 private Rect mAltTmpRect = new Rect();
237
238 // Fling to delete
239 private int FLING_TO_DELETE_FADE_OUT_DURATION = 350;
240 private float FLING_TO_DELETE_FRICTION = 0.035f;
241 // The degrees specifies how much deviation from the up vector to still consider a fling "up"
242 private float FLING_TO_DELETE_MAX_FLING_DEGREES = 65f;
243 protected int mFlingToDeleteThresholdVelocity = -1400;
244 // Drag to delete
245 private boolean mDeferringForDelete = false;
246 private int DELETE_SLIDE_IN_SIDE_PAGE_DURATION = 250;
247 private int DRAG_TO_DELETE_FADE_OUT_DURATION = 350;
248
249 // Drop to delete
250 private View mDeleteDropTarget;
251
252 private boolean mAutoComputePageSpacing = false;
253 private boolean mRecomputePageSpacing = false;
254
255 // Bouncer
256 private boolean mTopAlignPageWhenShrinkingForBouncer = false;
Winson Chungb44b5242011-06-13 11:32:14 -0700257
Winson Chung86f77532010-08-24 11:08:22 -0700258 public interface PageSwitchListener {
259 void onPageSwitch(View newPage, int newPageIndex);
Winson Chung321e9ee2010-08-09 13:37:56 -0700260 }
261
Winson Chung321e9ee2010-08-09 13:37:56 -0700262 public PagedView(Context context) {
263 this(context, null);
264 }
265
266 public PagedView(Context context, AttributeSet attrs) {
267 this(context, attrs, 0);
268 }
269
270 public PagedView(Context context, AttributeSet attrs, int defStyle) {
271 super(context, attrs, defStyle);
Winson Chungc9ca2982013-07-19 12:07:38 -0700272
Adam Cohen9c4949e2010-10-05 12:27:22 -0700273 TypedArray a = context.obtainStyledAttributes(attrs,
274 R.styleable.PagedView, defStyle, 0);
Adam Cohen60b07122011-11-14 17:26:06 -0800275 setPageSpacing(a.getDimensionPixelSize(R.styleable.PagedView_pageSpacing, 0));
Adam Cohen7d30a372013-07-01 17:03:59 -0700276 if (mPageSpacing < 0) {
277 mAutoComputePageSpacing = mRecomputePageSpacing = true;
278 }
Adam Cohen9c4949e2010-10-05 12:27:22 -0700279 mPageLayoutPaddingTop = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800280 R.styleable.PagedView_pageLayoutPaddingTop, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700281 mPageLayoutPaddingBottom = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800282 R.styleable.PagedView_pageLayoutPaddingBottom, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700283 mPageLayoutPaddingLeft = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800284 R.styleable.PagedView_pageLayoutPaddingLeft, 0);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700285 mPageLayoutPaddingRight = a.getDimensionPixelSize(
Winson Chung1908d072011-02-24 18:09:44 -0800286 R.styleable.PagedView_pageLayoutPaddingRight, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700287 mPageLayoutWidthGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700288 R.styleable.PagedView_pageLayoutWidthGap, 0);
Winson Chungdf4b83d2010-10-20 17:49:27 -0700289 mPageLayoutHeightGap = a.getDimensionPixelSize(
Winson Chung7d7541e2011-09-16 20:14:36 -0700290 R.styleable.PagedView_pageLayoutHeightGap, 0);
Winson Chungd2be3812013-07-16 11:11:32 -0700291 mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1);
Adam Cohen9c4949e2010-10-05 12:27:22 -0700292 a.recycle();
293
Winson Chung321e9ee2010-08-09 13:37:56 -0700294 setHapticFeedbackEnabled(false);
Michael Jurka0142d492010-08-25 17:46:15 -0700295 init();
Winson Chung321e9ee2010-08-09 13:37:56 -0700296 }
297
298 /**
299 * Initializes various states for this workspace.
300 */
Michael Jurka0142d492010-08-25 17:46:15 -0700301 protected void init() {
Winson Chung86f77532010-08-24 11:08:22 -0700302 mDirtyPageContent = new ArrayList<Boolean>();
303 mDirtyPageContent.ensureCapacity(32);
Adam Cohene0f66b52010-11-23 15:06:07 -0800304 mScroller = new Scroller(getContext(), new ScrollInterpolator());
Winson Chung86f77532010-08-24 11:08:22 -0700305 mCurrentPage = 0;
Winson Chung7da10252010-10-28 16:07:04 -0700306 mCenterPagesVertically = true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700307
308 final ViewConfiguration configuration = ViewConfiguration.get(getContext());
Adam Cohen7d30a372013-07-01 17:03:59 -0700309 mTouchSlop = configuration.getScaledPagingTouchSlop();
Winson Chung321e9ee2010-08-09 13:37:56 -0700310 mPagingTouchSlop = configuration.getScaledPagingTouchSlop();
311 mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
Adam Cohenb5ba0972011-09-07 18:02:31 -0700312 mDensity = getResources().getDisplayMetrics().density;
Adam Cohen265b9a62011-12-07 14:37:18 -0800313
Adam Cohen7d30a372013-07-01 17:03:59 -0700314 // Scale the fling-to-delete threshold by the density
315 mFlingToDeleteThresholdVelocity =
316 (int) (mFlingToDeleteThresholdVelocity * mDensity);
317
Adam Cohen265b9a62011-12-07 14:37:18 -0800318 mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
319 mMinFlingVelocity = (int) (MIN_FLING_VELOCITY * mDensity);
320 mMinSnapVelocity = (int) (MIN_SNAP_VELOCITY * mDensity);
Michael Jurka8b805b12012-04-18 14:23:14 -0700321 setOnHierarchyChangeListener(this);
Winson Chung321e9ee2010-08-09 13:37:56 -0700322 }
323
Winson Chungd2be3812013-07-16 11:11:32 -0700324 protected void onAttachedToWindow() {
325 // Hook up the page indicator
326 ViewGroup parent = (ViewGroup) getParent();
327 if (mPageIndicator == null && mPageIndicatorViewId > -1) {
328 mPageIndicator = (PageIndicator) parent.findViewById(mPageIndicatorViewId);
329 mPageIndicator.removeAllMarkers();
Winson Chung82dfe582013-07-26 15:07:49 -0700330
331 ArrayList<Integer> markers = new ArrayList<Integer>();
332 for (int i = 0; i < getChildCount(); ++i) {
333 markers.add(getPageIndicatorMarker(i));
334 }
335 mPageIndicator.addMarkers(markers);
Winson Chungd2be3812013-07-16 11:11:32 -0700336 }
337 }
338
339 protected void onDetachedFromWindow() {
340 // Unhook the page indicator
341 mPageIndicator = null;
342 }
343
Adam Cohen7d30a372013-07-01 17:03:59 -0700344 void setDeleteDropTarget(View v) {
345 mDeleteDropTarget = v;
346 }
347
348 // Convenience methods to map points from self to parent and vice versa
349 float[] mapPointFromViewToParent(View v, float x, float y) {
350 mTmpPoint[0] = x;
351 mTmpPoint[1] = y;
352 v.getMatrix().mapPoints(mTmpPoint);
353 mTmpPoint[0] += v.getLeft();
354 mTmpPoint[1] += v.getTop();
355 return mTmpPoint;
356 }
357 float[] mapPointFromParentToView(View v, float x, float y) {
358 mTmpPoint[0] = x - v.getLeft();
359 mTmpPoint[1] = y - v.getTop();
360 v.getMatrix().invert(mTmpInvMatrix);
361 mTmpInvMatrix.mapPoints(mTmpPoint);
362 return mTmpPoint;
363 }
364
365 void updateDragViewTranslationDuringDrag() {
366 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
367 float y = mLastMotionY - mDownMotionY;
368 mDragView.setTranslationX(x);
369 mDragView.setTranslationY(y);
370
371 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
372 }
373
374 public void setMinScale(float f) {
375 mMinScale = f;
376 requestLayout();
377 }
378
379 @Override
380 public void setScaleX(float scaleX) {
381 super.setScaleX(scaleX);
382 if (isReordering(true)) {
383 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
384 mLastMotionX = p[0];
385 mLastMotionY = p[1];
386 updateDragViewTranslationDuringDrag();
387 }
388 }
389
390 // Convenience methods to get the actual width/height of the PagedView (since it is measured
391 // to be larger to account for the minimum possible scale)
392 int getViewportWidth() {
393 return mViewport.width();
394 }
395 int getViewportHeight() {
396 return mViewport.height();
397 }
398
399 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
400 // PagedView both horizontally and vertically
401 int getViewportOffsetX() {
402 return (getMeasuredWidth() - getViewportWidth()) / 2;
403 }
404
405 int getViewportOffsetY() {
406 return (getMeasuredHeight() - getViewportHeight()) / 2;
407 }
408
Adam Cohenedb40762013-07-18 16:45:45 -0700409 PageIndicator getPageIndicator() {
410 return mPageIndicator;
411 }
Winson Chung82dfe582013-07-26 15:07:49 -0700412 protected int getPageIndicatorMarker(int pageIndex) {
413 return R.layout.page_indicator_marker;
414 }
Adam Cohenedb40762013-07-18 16:45:45 -0700415
Winson Chung86f77532010-08-24 11:08:22 -0700416 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
417 mPageSwitchListener = pageSwitchListener;
418 if (mPageSwitchListener != null) {
419 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700420 }
421 }
422
423 /**
Winson Chung52aee602013-01-30 12:01:02 -0800424 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
425 */
426 public boolean isLayoutRtl() {
427 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
428 }
429
430 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700431 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
432 * out pages.
433 */
434 protected void setDataIsReady() {
435 mIsDataReady = true;
436 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700437
Winson Chungf0ea4d32011-06-06 14:27:16 -0700438 protected boolean isDataReady() {
439 return mIsDataReady;
440 }
441
442 /**
Winson Chung86f77532010-08-24 11:08:22 -0700443 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700444 *
Winson Chung86f77532010-08-24 11:08:22 -0700445 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700446 */
Winson Chung86f77532010-08-24 11:08:22 -0700447 int getCurrentPage() {
448 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700449 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700450
Winson Chung360e63f2012-04-27 13:48:05 -0700451 int getNextPage() {
452 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
453 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700454
Winson Chung86f77532010-08-24 11:08:22 -0700455 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700456 return getChildCount();
457 }
458
Winson Chung86f77532010-08-24 11:08:22 -0700459 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700460 return getChildAt(index);
461 }
462
Adam Cohenae4f1552011-10-20 00:15:42 -0700463 protected int indexToPage(int index) {
464 return index;
465 }
466
Winson Chung321e9ee2010-08-09 13:37:56 -0700467 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800468 * Updates the scroll of the current page immediately to its final scroll position. We use this
469 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
470 * the previous tab page.
471 */
472 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700473 // If the current page is invalid, just reset the scroll position to zero
474 int newX = 0;
475 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700476 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700477 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800478 scrollTo(newX, 0);
479 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800480 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800481 }
482
483 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700484 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
485 * ends, {@link #resumeScrolling()} should be called, along with
486 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
487 */
488 void pauseScrolling() {
489 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700490 }
491
492 /**
493 * Enables scrolling again.
494 * @see #pauseScrolling()
495 */
496 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700497 }
498 /**
Winson Chung86f77532010-08-24 11:08:22 -0700499 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700500 */
Winson Chung86f77532010-08-24 11:08:22 -0700501 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800502 if (!mScroller.isFinished()) {
503 mScroller.abortAnimation();
504 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800505 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
506 // the default
507 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800508 return;
509 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700510
Adam Cohene61a9a22013-06-11 15:45:31 -0700511 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700512 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700513 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700514 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800515 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700516 }
517
Winson Chung8c87cd82013-07-23 16:20:10 -0700518 /**
519 * The restore page will be set in place of the current page at the next (likely first)
520 * layout.
521 */
522 void setRestorePage(int restorePage) {
523 mRestorePage = restorePage;
524 }
525
Michael Jurka0142d492010-08-25 17:46:15 -0700526 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700527 if (mPageSwitchListener != null) {
528 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700529 }
Winson Chungd2be3812013-07-16 11:11:32 -0700530
531 // Update the page indicator (when we aren't reordering)
532 if (mPageIndicator != null && !isReordering(false)) {
533 mPageIndicator.setActiveMarker(getNextPage());
534 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700535 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800536 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700537 if (!mIsPageMoving) {
538 mIsPageMoving = true;
539 onPageBeginMoving();
540 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700541 }
542
Michael Jurkace7e05f2011-02-01 22:02:35 -0800543 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700544 if (mIsPageMoving) {
545 mIsPageMoving = false;
546 onPageEndMoving();
547 }
Michael Jurka0142d492010-08-25 17:46:15 -0700548 }
549
Adam Cohen26976d92011-03-22 15:33:33 -0700550 protected boolean isPageMoving() {
551 return mIsPageMoving;
552 }
553
Michael Jurka0142d492010-08-25 17:46:15 -0700554 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700555 protected void onPageBeginMoving() {
556 }
557
558 // a method that subclasses can override to add behavior
559 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700560 }
561
Winson Chung321e9ee2010-08-09 13:37:56 -0700562 /**
Winson Chung86f77532010-08-24 11:08:22 -0700563 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700564 *
565 * @param l The listener used to respond to long clicks.
566 */
567 @Override
568 public void setOnLongClickListener(OnLongClickListener l) {
569 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700570 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700571 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700572 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700573 }
574 }
575
576 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800577 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700578 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800579 }
580
581 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700582 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700583 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800584 mUnboundedScrollX = x;
585
Adam Cohen0ffac432013-07-10 11:19:26 -0700586 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
587 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
588 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800589 super.scrollTo(0, y);
590 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700591 if (isRtl) {
592 overScroll(x - mMaxScrollX);
593 } else {
594 overScroll(x);
595 }
Adam Cohen68d73932010-11-15 10:50:58 -0800596 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700597 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800598 super.scrollTo(mMaxScrollX, y);
599 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700600 if (isRtl) {
601 overScroll(x);
602 } else {
603 overScroll(x - mMaxScrollX);
604 }
Adam Cohen68d73932010-11-15 10:50:58 -0800605 }
606 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800607 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800608 super.scrollTo(x, y);
609 }
610
Michael Jurka0142d492010-08-25 17:46:15 -0700611 mTouchX = x;
612 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700613
614 // Update the last motion events when scrolling
615 if (isReordering(true)) {
616 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
617 mLastMotionX = p[0];
618 mLastMotionY = p[1];
619 updateDragViewTranslationDuringDrag();
620 }
Michael Jurka0142d492010-08-25 17:46:15 -0700621 }
622
623 // we moved this functionality to a helper function so SmoothPagedView can reuse it
624 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700625 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700626 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700627 if (getScrollX() != mScroller.getCurrX()
628 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700629 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700630 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
631 }
Michael Jurka0142d492010-08-25 17:46:15 -0700632 invalidate();
633 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700634 } else if (mNextPage != INVALID_PAGE) {
635 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700636 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700637 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700638
Winson Chung9c0565f2013-07-19 13:49:06 -0700639 // Load the associated pages if necessary
640 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
641 loadAssociatedPages(mCurrentPage);
642 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
643 }
644
Adam Cohen73aa9752010-11-24 16:26:58 -0800645 // We don't want to trigger a page end moving unless the page has settled
646 // and the user has stopped scrolling
647 if (mTouchState == TOUCH_STATE_REST) {
648 pageEndMoving();
649 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700650
Adam Cohen7d30a372013-07-01 17:03:59 -0700651 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700652 // Notify the user when the page changes
653 AccessibilityManager accessibilityManager = (AccessibilityManager)
654 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
655 if (accessibilityManager.isEnabled()) {
656 AccessibilityEvent ev =
657 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
658 ev.getText().add(getCurrentPageDescription());
659 sendAccessibilityEventUnchecked(ev);
660 }
Michael Jurka0142d492010-08-25 17:46:15 -0700661 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700662 }
Michael Jurka0142d492010-08-25 17:46:15 -0700663 return false;
664 }
665
666 @Override
667 public void computeScroll() {
668 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700669 }
670
Adam Cohen7d30a372013-07-01 17:03:59 -0700671 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
672 return mTopAlignPageWhenShrinkingForBouncer;
673 }
674
Adam Cohen96d30a12013-07-16 18:13:21 -0700675 public static class LayoutParams extends ViewGroup.LayoutParams {
676 public boolean isFullScreenPage = false;
677
678 /**
679 * {@inheritDoc}
680 */
681 public LayoutParams(int width, int height) {
682 super(width, height);
683 }
684
685 public LayoutParams(ViewGroup.LayoutParams source) {
686 super(source);
687 }
688 }
689
690 protected LayoutParams generateDefaultLayoutParams() {
691 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
692 }
693
Adam Cohenedb40762013-07-18 16:45:45 -0700694 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700695 LayoutParams lp = generateDefaultLayoutParams();
696 lp.isFullScreenPage = true;
697 super.addView(page, 0, lp);
698 }
699
Winson Chung321e9ee2010-08-09 13:37:56 -0700700 @Override
701 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700702 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700703 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
704 return;
705 }
706
Adam Cohen7d30a372013-07-01 17:03:59 -0700707 // We measure the dimensions of the PagedView to be larger than the pages so that when we
708 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700709 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
710 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
711 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700712 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700713 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
714 // viewport, we can be at most one and a half screens offset once we scale down
715 DisplayMetrics dm = getResources().getDisplayMetrics();
716 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
717 int parentWidthSize = (int) (1.5f * maxSize);
718 int parentHeightSize = maxSize;
719 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
720 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
721 mViewport.set(0, 0, widthSize, heightSize);
722
723 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
724 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
725 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700726 }
727
Winson Chung8aad6102012-05-11 16:27:49 -0700728 // Return early if we aren't given a proper dimension
729 if (widthSize <= 0 || heightSize <= 0) {
730 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
731 return;
732 }
733
Adam Lesinski6b879f02010-11-04 16:15:23 -0700734 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
735 * of the All apps view on XLarge displays to not take up more space then it needs. Width
736 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
737 * each page to have the same width.
738 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700739 final int verticalPadding = getPaddingTop() + getPaddingBottom();
740 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700741
742 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700743 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700744 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700745 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
746 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
747 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
748 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700749 final int childCount = getChildCount();
750 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700751 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700752 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700753 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
754
755 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700756 int childHeightMode;
757 int childWidth;
758 int childHeight;
759
760 if (!lp.isFullScreenPage) {
761 if (lp.width == LayoutParams.WRAP_CONTENT) {
762 childWidthMode = MeasureSpec.AT_MOST;
763 } else {
764 childWidthMode = MeasureSpec.EXACTLY;
765 }
766
767 if (lp.height == LayoutParams.WRAP_CONTENT) {
768 childHeightMode = MeasureSpec.AT_MOST;
769 } else {
770 childHeightMode = MeasureSpec.EXACTLY;
771 }
772
773 childWidth = widthSize - horizontalPadding;
774 childHeight = heightSize - verticalPadding;
775
Michael Jurka5f1c5092010-09-03 14:15:02 -0700776 } else {
777 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700778 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700779
780 childWidth = getViewportWidth();
781 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700782 }
783
784 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700785 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
786 final int childHeightMeasureSpec =
787 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700788 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700789 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700790 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700791
Winson Chunga128a7b2012-04-30 15:23:15 -0700792 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700793 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700794 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700795 // The gap between pages in the PagedView should be equal to the gap from the page
796 // to the edge of the screen (so it is not visible in the current screen). To
797 // account for unequal padding on each side of the paged view, we take the maximum
798 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700799 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700800 int spacing = Math.max(offset, widthSize - offset -
801 getChildAt(0).getMeasuredWidth());
802 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700803 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700804 }
805 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700806 }
807
Adam Cohen60b07122011-11-14 17:26:06 -0800808 public void setPageSpacing(int pageSpacing) {
809 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700810 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800811 }
812
Winson Chung321e9ee2010-08-09 13:37:56 -0700813 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700814 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700815 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700816 return;
817 }
818
Winson Chung785d2eb2011-04-14 16:08:02 -0700819 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700820 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700821
Adam Cohenedb40762013-07-18 16:45:45 -0700822 int screenWidth = getViewportWidth();
823
Adam Cohen7d30a372013-07-01 17:03:59 -0700824 int offsetX = getViewportOffsetX();
825 int offsetY = getViewportOffsetY();
826
827 // Update the viewport offsets
828 mViewport.offset(offsetX, offsetY);
829
Adam Cohen0ffac432013-07-10 11:19:26 -0700830 final boolean isRtl = isLayoutRtl();
831
832 final int startIndex = isRtl ? childCount - 1 : 0;
833 final int endIndex = isRtl ? -1 : childCount;
834 final int delta = isRtl ? -1 : 1;
835
Adam Cohen7d30a372013-07-01 17:03:59 -0700836 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700837 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
838
839 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
840 mPageScrolls = new int[getChildCount()];
841 }
842
Adam Cohen0ffac432013-07-10 11:19:26 -0700843 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700844
Adam Cohen22f823d2011-09-01 17:22:18 -0700845 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700846 LayoutParams lp = (LayoutParams) child.getLayoutParams();
847 int childTop;
848
849 if (lp.isFullScreenPage) {
850 childTop = offsetY;
851 } else {
852 childTop = offsetY + getPaddingTop();
853 if (mCenterPagesVertically) {
854 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
855 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700856 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700857
Winson Chung321e9ee2010-08-09 13:37:56 -0700858 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700859 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700860 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800861
Winson Chung785d2eb2011-04-14 16:08:02 -0700862 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700863 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800864 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700865
866 // We assume the left and right padding are equal, and hence center the pages
867 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700868 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700869 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
870
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700871 if (i != endIndex - delta) {
872 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
873 childLeft += childWidth + nextScrollOffset;
874 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700875 }
876 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700877
878 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
879 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800880 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700881 setHorizontalScrollBarEnabled(true);
882 mFirstLayout = false;
883 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700884
885 if (childCount > 0) {
886 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700887 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700888 } else {
889 mMaxScrollX = 0;
890 }
891
892 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
893 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700894 if (mRestorePage > -1) {
895 setCurrentPage(mRestorePage);
896 mRestorePage = -1;
897 } else {
898 setCurrentPage(getNextPage());
899 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700900 }
901 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700902 }
903
Adam Cohenf34bab52010-09-30 14:11:56 -0700904 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700905 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
906
907 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700908 for (int i = 0; i < getChildCount(); i++) {
909 View child = getChildAt(i);
910 if (child != null) {
911 float scrollProgress = getScrollProgress(screenCenter, child, i);
912 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800913 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700914 }
915 }
916 invalidate();
917 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700918 }
919
Winson Chunge3193b92010-09-10 11:44:42 -0700920 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700921 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700922 // Update the page indicator, we don't update the page indicator as we
923 // add/remove pages
924 if (mPageIndicator != null && !isReordering(false)) {
Winson Chung82dfe582013-07-26 15:07:49 -0700925 int pageIndex = indexOfChild(child);
926 mPageIndicator.addMarker(pageIndex, getPageIndicatorMarker(pageIndex));
Winson Chungd2be3812013-07-16 11:11:32 -0700927 }
928
Adam Cohen2591f6a2011-10-25 14:36:40 -0700929 // This ensures that when children are added, they get the correct transforms / alphas
930 // in accordance with any scroll effects.
931 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700932 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700933
Adam Cohen2591f6a2011-10-25 14:36:40 -0700934 invalidate();
935 }
936
Michael Jurka8b805b12012-04-18 14:23:14 -0700937 @Override
938 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700939 mForceScreenScrolled = true;
940 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700941 }
942
Winson Chungd2be3812013-07-16 11:11:32 -0700943 private void removeMarkerForView(int index) {
944 // Update the page indicator, we don't update the page indicator as we
945 // add/remove pages
946 if (mPageIndicator != null && !isReordering(false)) {
947 mPageIndicator.removeMarker(index);
948 }
949 }
950
951 @Override
952 public void removeView(View v) {
953 // XXX: We should find a better way to hook into this before the view
954 // gets removed form its parent...
955 removeMarkerForView(indexOfChild(v));
956 super.removeView(v);
957 }
958 @Override
959 public void removeViewInLayout(View v) {
960 // XXX: We should find a better way to hook into this before the view
961 // gets removed form its parent...
962 removeMarkerForView(indexOfChild(v));
963 super.removeViewInLayout(v);
964 }
965 @Override
966 public void removeViewAt(int index) {
967 // XXX: We should find a better way to hook into this before the view
968 // gets removed form its parent...
969 removeViewAt(index);
970 super.removeViewAt(index);
971 }
972 @Override
973 public void removeAllViewsInLayout() {
974 // Update the page indicator, we don't update the page indicator as we
975 // add/remove pages
976 if (mPageIndicator != null) {
977 mPageIndicator.removeAllMarkers();
978 }
979
980 super.removeAllViewsInLayout();
981 }
982
Adam Cohen73894962011-10-31 13:17:17 -0700983 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700984 if (index < 0 || index > getChildCount() - 1) return 0;
985
Adam Cohen0ffac432013-07-10 11:19:26 -0700986 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700987
Adam Cohenf698c6e2013-07-17 18:44:25 -0700988 if (isRtl) index = getChildCount() - index - 1;
989 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700990
Adam Cohenf698c6e2013-07-17 18:44:25 -0700991 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700992 }
993
Winson Chungc9ca2982013-07-19 12:07:38 -0700994 void getReorderablePages(int[] range) {
995 range[0] = 0;
996 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -0700997 }
998
Michael Jurkadde558b2011-11-09 22:09:06 -0800999 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -07001000 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -07001001 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -07001002
Michael Jurkac4fb9172010-09-02 17:19:20 -07001003 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -07001004 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -07001005 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -07001006 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001007
Winson Chungc9ca2982013-07-19 12:07:38 -07001008 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1009 View currPage = getPageAt(leftScreen);
1010
1011 // Check if the right edge of the page is in the viewport
1012 mTmpIntPoint[0] = currPage.getMeasuredWidth();
Winson Chungc763c4e2013-07-19 13:49:06 -07001013 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001014 if (mTmpIntPoint[0] < 0) {
1015 break;
1016 }
1017 }
1018 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1019 View currPage = getPageAt(rightScreen);
1020
1021 // Check if the left edge of the page is in the viewport
1022 mTmpIntPoint[0] = 0;
Winson Chungc763c4e2013-07-19 13:49:06 -07001023 Utilities.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
Winson Chungc9ca2982013-07-19 12:07:38 -07001024 if (mTmpIntPoint[0] >= viewportWidth) {
1025 break;
1026 }
1027 }
1028 range[0] = Math.max(0, leftScreen);
1029 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001030 } else {
1031 range[0] = -1;
1032 range[1] = -1;
1033 }
1034 }
1035
Michael Jurka920d7f42012-05-14 16:29:55 -07001036 protected boolean shouldDrawChild(View child) {
1037 return child.getAlpha() > 0;
1038 }
1039
Michael Jurkadde558b2011-11-09 22:09:06 -08001040 @Override
1041 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001042 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001043 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1044 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001045 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001046
1047 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001048 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1049 // set it for the next frame
1050 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001051 screenScrolled(screenCenter);
1052 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001053 }
1054
1055 // Find out which screens are visible; as an optimization we only call draw on them
1056 final int pageCount = getChildCount();
1057 if (pageCount > 0) {
1058 getVisiblePages(mTempVisiblePagesRange);
1059 final int leftScreen = mTempVisiblePagesRange[0];
1060 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001061 if (leftScreen != -1 && rightScreen != -1) {
1062 final long drawingTime = getDrawingTime();
1063 // Clip to the bounds
1064 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001065 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1066 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001067
Adam Cohen7d30a372013-07-01 17:03:59 -07001068 // Draw all the children, leaving the drag view for last
1069 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001070 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001071 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001072 if (mForceDrawAllChildrenNextFrame ||
1073 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001074 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001075 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001076 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001077 // Draw the drag view on top (if there is one)
1078 if (mDragView != null) {
1079 drawChild(canvas, mDragView, drawingTime);
1080 }
1081
Michael Jurka5e368ff2012-05-14 23:13:15 -07001082 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001083 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001084 }
Michael Jurka0142d492010-08-25 17:46:15 -07001085 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001086 }
1087
1088 @Override
1089 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001090 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001091 if (page != mCurrentPage || !mScroller.isFinished()) {
1092 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001093 return true;
1094 }
1095 return false;
1096 }
1097
1098 @Override
1099 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001100 int focusablePage;
1101 if (mNextPage != INVALID_PAGE) {
1102 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001103 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001104 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001105 }
Winson Chung86f77532010-08-24 11:08:22 -07001106 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001107 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001108 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001109 }
1110 return false;
1111 }
1112
1113 @Override
1114 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001115 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001116 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001117 if (getCurrentPage() > 0) {
1118 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001119 return true;
1120 }
1121 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001122 if (getCurrentPage() < getPageCount() - 1) {
1123 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001124 return true;
1125 }
1126 }
1127 return super.dispatchUnhandledMove(focused, direction);
1128 }
1129
1130 @Override
1131 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001132 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001133 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001134 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001135 }
1136 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001137 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001138 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001139 }
1140 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001141 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001142 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001143 }
1144 }
1145 }
1146
1147 /**
1148 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001149 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001150 *
Winson Chung86f77532010-08-24 11:08:22 -07001151 * This happens when live folders requery, and if they're off page, they
1152 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001153 */
1154 @Override
1155 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001156 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001157 View v = focused;
1158 while (true) {
1159 if (v == current) {
1160 super.focusableViewAvailable(focused);
1161 return;
1162 }
1163 if (v == this) {
1164 return;
1165 }
1166 ViewParent parent = v.getParent();
1167 if (parent instanceof View) {
1168 v = (View)v.getParent();
1169 } else {
1170 return;
1171 }
1172 }
1173 }
1174
1175 /**
1176 * {@inheritDoc}
1177 */
1178 @Override
1179 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1180 if (disallowIntercept) {
1181 // We need to make sure to cancel our long press if
1182 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001183 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001184 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001185 }
1186 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1187 }
1188
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001189 /**
1190 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1191 */
1192 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001193 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001194 if (isLayoutRtl()) {
1195 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001196 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001197 }
Adam Cohenedb40762013-07-18 16:45:45 -07001198 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001199 }
1200
1201 /**
1202 * Return true if a tap at (x, y) should trigger a flip to the next page.
1203 */
1204 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001205 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001206 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001207 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001208 }
1209 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001210 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001211 }
Winson Chung52aee602013-01-30 12:01:02 -08001212
Adam Cohen7d30a372013-07-01 17:03:59 -07001213 /** Returns whether x and y originated within the buffered viewport */
1214 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1215 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1216 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1217 return mTmpRect.contains(x, y);
1218 }
1219
1220 /** Returns whether x and y originated within the current page view bounds */
1221 private boolean isTouchPointInCurrentPage(int x, int y) {
1222 View v = getPageAt(getCurrentPage());
1223 if (v != null) {
1224 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1225 v.getBottom());
1226 return mTmpRect.contains(x, y);
1227 }
1228 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001229 }
1230
Winson Chung321e9ee2010-08-09 13:37:56 -07001231 @Override
1232 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001233 if (DISABLE_TOUCH_INTERACTION) {
1234 return false;
1235 }
1236
Winson Chung321e9ee2010-08-09 13:37:56 -07001237 /*
1238 * This method JUST determines whether we want to intercept the motion.
1239 * If we return true, onTouchEvent will be called and we do the actual
1240 * scrolling there.
1241 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001242 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001243
Winson Chung45e1d6e2010-11-09 17:19:49 -08001244 // Skip touch handling if there are no pages to swipe
1245 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1246
Winson Chung321e9ee2010-08-09 13:37:56 -07001247 /*
1248 * Shortcut the most recurring case: the user is in the dragging
1249 * state and he is moving his finger. We want to intercept this
1250 * motion.
1251 */
1252 final int action = ev.getAction();
1253 if ((action == MotionEvent.ACTION_MOVE) &&
1254 (mTouchState == TOUCH_STATE_SCROLLING)) {
1255 return true;
1256 }
1257
Winson Chung321e9ee2010-08-09 13:37:56 -07001258 switch (action & MotionEvent.ACTION_MASK) {
1259 case MotionEvent.ACTION_MOVE: {
1260 /*
1261 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1262 * whether the user has moved far enough from his original down touch.
1263 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001264 if (mActivePointerId != INVALID_POINTER) {
1265 determineScrollingStart(ev);
1266 break;
1267 }
1268 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1269 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1270 // i.e. fall through to the next case (don't break)
1271 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1272 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001273 }
1274
1275 case MotionEvent.ACTION_DOWN: {
1276 final float x = ev.getX();
1277 final float y = ev.getY();
1278 // Remember location of down touch
1279 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001280 mDownMotionY = y;
1281 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001282 mLastMotionX = x;
1283 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001284 float[] p = mapPointFromViewToParent(this, x, y);
1285 mParentDownMotionX = p[0];
1286 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001287 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001288 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001289 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001290
1291 // Determine if the down event is within the threshold to be an edge swipe
1292 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1293 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1294 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1295 mDownEventOnEdge = true;
1296 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001297
1298 /*
1299 * If being flinged and user touches the screen, initiate drag;
1300 * otherwise don't. mScroller.isFinished should be false when
1301 * being flinged.
1302 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001303 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001304 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1305 if (finishedScrolling) {
1306 mTouchState = TOUCH_STATE_REST;
1307 mScroller.abortAnimation();
1308 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001309 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1310 mTouchState = TOUCH_STATE_SCROLLING;
1311 } else {
1312 mTouchState = TOUCH_STATE_REST;
1313 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001314 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001315
Winson Chung86f77532010-08-24 11:08:22 -07001316 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001317 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001318 if (!DISABLE_TOUCH_SIDE_PAGES) {
1319 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1320 if (getChildCount() > 0) {
1321 if (hitsPreviousPage(x, y)) {
1322 mTouchState = TOUCH_STATE_PREV_PAGE;
1323 } else if (hitsNextPage(x, y)) {
1324 mTouchState = TOUCH_STATE_NEXT_PAGE;
1325 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001326 }
1327 }
1328 }
1329 break;
1330 }
1331
Winson Chung321e9ee2010-08-09 13:37:56 -07001332 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001333 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001334 resetTouchState();
1335 // Just intercept the touch event on up if we tap outside the strict viewport
1336 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1337 return true;
1338 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001339 break;
1340
1341 case MotionEvent.ACTION_POINTER_UP:
1342 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001343 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001344 break;
1345 }
1346
1347 /*
1348 * The only time we want to intercept motion events is if we are in the
1349 * drag mode.
1350 */
1351 return mTouchState != TOUCH_STATE_REST;
1352 }
1353
Adam Cohenf8d28232011-02-01 21:47:00 -08001354 protected void determineScrollingStart(MotionEvent ev) {
1355 determineScrollingStart(ev, 1.0f);
1356 }
1357
Winson Chung321e9ee2010-08-09 13:37:56 -07001358 /*
1359 * Determines if we should change the touch state to start scrolling after the
1360 * user moves their touch point too far.
1361 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001362 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001363 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001364 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001365 if (pointerIndex == -1) return;
1366
1367 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001368 final float x = ev.getX(pointerIndex);
1369 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001370 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1371
1372 // If we're only allowing edge swipes, we break out early if the down event wasn't
1373 // at the edge.
1374 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1375
Winson Chung321e9ee2010-08-09 13:37:56 -07001376 final int xDiff = (int) Math.abs(x - mLastMotionX);
1377 final int yDiff = (int) Math.abs(y - mLastMotionY);
1378
Adam Cohenf8d28232011-02-01 21:47:00 -08001379 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001380 boolean xPaged = xDiff > mPagingTouchSlop;
1381 boolean xMoved = xDiff > touchSlop;
1382 boolean yMoved = yDiff > touchSlop;
1383
Adam Cohenf8d28232011-02-01 21:47:00 -08001384 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001385 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001386 // Scroll if the user moved far enough along the X axis
1387 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001388 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001389 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001390 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001391 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001392 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1393 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001394 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001395 }
1396 }
1397
Adam Cohen7d30a372013-07-01 17:03:59 -07001398 protected float getMaxScrollProgress() {
1399 return 1.0f;
1400 }
1401
Adam Cohenf8d28232011-02-01 21:47:00 -08001402 protected void cancelCurrentPageLongPress() {
1403 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001404 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001405 // Try canceling the long press. It could also have been scheduled
1406 // by a distant descendant, so use the mAllowLongPress flag to block
1407 // everything
1408 final View currentPage = getPageAt(mCurrentPage);
1409 if (currentPage != null) {
1410 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001411 }
1412 }
1413 }
1414
Adam Cohen7d30a372013-07-01 17:03:59 -07001415 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1416 final int halfScreenSize = getViewportWidth() / 2;
1417
1418 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1419 screenCenter = Math.max(halfScreenSize, screenCenter);
1420
1421 return getScrollProgress(screenCenter, v, page);
1422 }
1423
Adam Cohenb5ba0972011-09-07 18:02:31 -07001424 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001425 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001426
Adam Cohen96d30a12013-07-16 18:13:21 -07001427 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001428 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001429
1430 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001431 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1432 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001433 return scrollProgress;
1434 }
1435
Adam Cohenedb40762013-07-18 16:45:45 -07001436 public int getScrollForPage(int index) {
1437 if (mPageScrolls == null || index >= mPageScrolls.length) {
1438 return 0;
1439 } else {
1440 return mPageScrolls[index];
1441 }
1442 }
1443
Adam Cohene0f66b52010-11-23 15:06:07 -08001444 // This curve determines how the effect of scrolling over the limits of the page dimishes
1445 // as the user pulls further and further from the bounds
1446 private float overScrollInfluenceCurve(float f) {
1447 f -= 1.0f;
1448 return f * f * f + 1.0f;
1449 }
1450
Adam Cohenb5ba0972011-09-07 18:02:31 -07001451 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001452 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001453
1454 // We want to reach the max over scroll effect when the user has
1455 // over scrolled half the size of the screen
1456 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1457
1458 if (f == 0) return;
1459
1460 // Clamp this factor, f, to -1 < f < 1
1461 if (Math.abs(f) >= 1) {
1462 f /= Math.abs(f);
1463 }
1464
1465 int overScrollAmount = (int) Math.round(f * screenSize);
1466 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001467 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001468 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001469 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001470 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001471 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001472 }
1473 invalidate();
1474 }
1475
1476 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001477 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001478
1479 float f = (amount / screenSize);
1480
1481 if (f == 0) return;
1482 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1483
Adam Cohen7bfc9792011-01-28 13:52:37 -08001484 // Clamp this factor, f, to -1 < f < 1
1485 if (Math.abs(f) >= 1) {
1486 f /= Math.abs(f);
1487 }
1488
Adam Cohene0f66b52010-11-23 15:06:07 -08001489 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001490 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001491 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001492 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001493 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001494 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001495 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001496 }
1497 invalidate();
1498 }
1499
Adam Cohenb5ba0972011-09-07 18:02:31 -07001500 protected void overScroll(float amount) {
1501 dampedOverScroll(amount);
1502 }
1503
Michael Jurkac5b262c2011-01-12 20:24:50 -08001504 protected float maxOverScroll() {
1505 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001506 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001507 float f = 1.0f;
1508 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1509 return OVERSCROLL_DAMP_FACTOR * f;
1510 }
1511
Winson Chung321e9ee2010-08-09 13:37:56 -07001512 @Override
1513 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001514 if (DISABLE_TOUCH_INTERACTION) {
1515 return false;
1516 }
1517
Winson Chung45e1d6e2010-11-09 17:19:49 -08001518 // Skip touch handling if there are no pages to swipe
1519 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1520
Michael Jurkab8f06722010-10-10 15:58:46 -07001521 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001522
1523 final int action = ev.getAction();
1524
1525 switch (action & MotionEvent.ACTION_MASK) {
1526 case MotionEvent.ACTION_DOWN:
1527 /*
1528 * If being flinged and user touches, stop the fling. isFinished
1529 * will be false if being flinged.
1530 */
1531 if (!mScroller.isFinished()) {
1532 mScroller.abortAnimation();
1533 }
1534
1535 // Remember where the motion event started
1536 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001537 mDownMotionY = mLastMotionY = ev.getY();
1538 mDownScrollX = getScrollX();
1539 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1540 mParentDownMotionX = p[0];
1541 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001542 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001543 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001544 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001545
1546 // Determine if the down event is within the threshold to be an edge swipe
1547 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1548 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1549 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1550 mDownEventOnEdge = true;
1551 }
1552
Michael Jurka0142d492010-08-25 17:46:15 -07001553 if (mTouchState == TOUCH_STATE_SCROLLING) {
1554 pageBeginMoving();
1555 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001556 break;
1557
1558 case MotionEvent.ACTION_MOVE:
1559 if (mTouchState == TOUCH_STATE_SCROLLING) {
1560 // Scroll to follow the motion event
1561 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001562
1563 if (pointerIndex == -1) return true;
1564
Winson Chung321e9ee2010-08-09 13:37:56 -07001565 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001566 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001567
Adam Cohenaefd4e12011-02-14 16:39:38 -08001568 mTotalMotionX += Math.abs(deltaX);
1569
Winson Chungc0844aa2011-02-02 15:25:58 -08001570 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1571 // keep the remainder because we are actually testing if we've moved from the last
1572 // scrolled position (which is discrete).
1573 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001574 mTouchX += deltaX;
1575 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1576 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001577 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001578 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001579 } else {
1580 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001581 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001582 mLastMotionX = x;
1583 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001584 } else {
1585 awakenScrollBars();
1586 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001587 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1588 // Update the last motion position
1589 mLastMotionX = ev.getX();
1590 mLastMotionY = ev.getY();
1591
1592 // Update the parent down so that our zoom animations take this new movement into
1593 // account
1594 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1595 mParentDownMotionX = pt[0];
1596 mParentDownMotionY = pt[1];
1597 updateDragViewTranslationDuringDrag();
1598
1599 // Find the closest page to the touch point
1600 final int dragViewIndex = indexOfChild(mDragView);
1601 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1602 getViewportWidth());
1603 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1604 + bufferSize);
1605 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1606 - bufferSize);
1607
1608 // Change the drag view if we are hovering over the drop target
1609 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1610 (int) mParentDownMotionX, (int) mParentDownMotionY);
1611 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1612
1613 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1614 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1615 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1616 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1617 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1618 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1619
1620 float parentX = mParentDownMotionX;
1621 int pageIndexToSnapTo = -1;
1622 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1623 pageIndexToSnapTo = dragViewIndex - 1;
1624 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1625 pageIndexToSnapTo = dragViewIndex + 1;
1626 }
1627
1628 final int pageUnderPointIndex = pageIndexToSnapTo;
1629 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1630 mTempVisiblePagesRange[0] = 0;
1631 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07001632 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001633 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1634 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1635 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1636 mSidePageHoverIndex = pageUnderPointIndex;
1637 mSidePageHoverRunnable = new Runnable() {
1638 @Override
1639 public void run() {
1640 // Update the down scroll position to account for the fact that the
1641 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001642 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001643
1644 // Setup the scroll to the correct page before we swap the views
1645 snapToPage(pageUnderPointIndex);
1646
1647 // For each of the pages between the paged view and the drag view,
1648 // animate them from the previous position to the new position in
1649 // the layout (as a result of the drag view moving in the layout)
1650 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1651 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1652 dragViewIndex + 1 : pageUnderPointIndex;
1653 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1654 dragViewIndex - 1 : pageUnderPointIndex;
1655 for (int i = lowerIndex; i <= upperIndex; ++i) {
1656 View v = getChildAt(i);
1657 // dragViewIndex < pageUnderPointIndex, so after we remove the
1658 // drag view all subsequent views to pageUnderPointIndex will
1659 // shift down.
1660 int oldX = getViewportOffsetX() + getChildOffset(i);
1661 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1662
1663 // Animate the view translation from its old position to its new
1664 // position
1665 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1666 if (anim != null) {
1667 anim.cancel();
1668 }
1669
1670 v.setTranslationX(oldX - newX);
1671 anim = new AnimatorSet();
1672 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1673 anim.playTogether(
1674 ObjectAnimator.ofFloat(v, "translationX", 0f));
1675 anim.start();
1676 v.setTag(anim);
1677 }
1678
1679 removeView(mDragView);
1680 onRemoveView(mDragView, false);
1681 addView(mDragView, pageUnderPointIndex);
1682 onAddView(mDragView, pageUnderPointIndex);
1683 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001684 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001685 }
1686 };
1687 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1688 }
1689 } else {
1690 removeCallbacks(mSidePageHoverRunnable);
1691 mSidePageHoverIndex = -1;
1692 }
Adam Cohen564976a2010-10-13 18:52:07 -07001693 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001694 determineScrollingStart(ev);
1695 }
1696 break;
1697
1698 case MotionEvent.ACTION_UP:
1699 if (mTouchState == TOUCH_STATE_SCROLLING) {
1700 final int activePointerId = mActivePointerId;
1701 final int pointerIndex = ev.findPointerIndex(activePointerId);
1702 final float x = ev.getX(pointerIndex);
1703 final VelocityTracker velocityTracker = mVelocityTracker;
1704 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1705 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001706 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001707 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001708 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1709 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001710
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001711 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1712
Adam Cohen00481b32011-11-18 12:03:48 -08001713 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001714 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001715
Adam Cohenaefd4e12011-02-14 16:39:38 -08001716 // In the case that the page is moved far to one direction and then is flung
1717 // in the opposite direction, we use a threshold to determine whether we should
1718 // just return to the starting page, or if we should skip one further.
1719 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001720 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001721 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001722 returnToOriginalPage = true;
1723 }
1724
Adam Cohenaefd4e12011-02-14 16:39:38 -08001725 int finalPage;
1726 // We give flings precedence over large moves, which is why we short-circuit our
1727 // test for a large move if a fling has been registered. That is, a large
1728 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001729 final boolean isRtl = isLayoutRtl();
1730 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1731 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1732 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1733 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001734 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1735 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001736 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1737 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001738 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001739 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1740 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001741 } else {
1742 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001743 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001744 // at this point we have not moved beyond the touch slop
1745 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1746 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001747 int nextPage = Math.max(0, mCurrentPage - 1);
1748 if (nextPage != mCurrentPage) {
1749 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001750 } else {
1751 snapToDestination();
1752 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001753 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001754 // at this point we have not moved beyond the touch slop
1755 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1756 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001757 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1758 if (nextPage != mCurrentPage) {
1759 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001760 } else {
1761 snapToDestination();
1762 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001763 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1764 // Update the last motion position
1765 mLastMotionX = ev.getX();
1766 mLastMotionY = ev.getY();
1767
1768 // Update the parent down so that our zoom animations take this new movement into
1769 // account
1770 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1771 mParentDownMotionX = pt[0];
1772 mParentDownMotionY = pt[1];
1773 updateDragViewTranslationDuringDrag();
1774 boolean handledFling = false;
1775 if (!DISABLE_FLING_TO_DELETE) {
1776 // Check the velocity and see if we are flinging-to-delete
1777 PointF flingToDeleteVector = isFlingingToDelete();
1778 if (flingToDeleteVector != null) {
1779 onFlingToDelete(flingToDeleteVector);
1780 handledFling = true;
1781 }
1782 }
1783 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1784 (int) mParentDownMotionY)) {
1785 onDropToDelete();
1786 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001787 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001788 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001789 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001790
1791 // Remove the callback to wait for the side page hover timeout
1792 removeCallbacks(mSidePageHoverRunnable);
1793 // End any intermediate reordering states
1794 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001795 break;
1796
1797 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001798 if (mTouchState == TOUCH_STATE_SCROLLING) {
1799 snapToDestination();
1800 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001801 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001802 break;
1803
1804 case MotionEvent.ACTION_POINTER_UP:
1805 onSecondaryPointerUp(ev);
1806 break;
1807 }
1808
1809 return true;
1810 }
1811
Adam Cohen7d30a372013-07-01 17:03:59 -07001812 public void onFlingToDelete(View v) {}
1813 public void onRemoveView(View v, boolean deletePermanently) {}
1814 public void onRemoveViewAnimationCompleted() {}
1815 public void onAddView(View v, int index) {}
1816
1817 private void resetTouchState() {
1818 releaseVelocityTracker();
1819 endReordering();
1820 mTouchState = TOUCH_STATE_REST;
1821 mActivePointerId = INVALID_POINTER;
1822 mDownEventOnEdge = false;
1823 }
1824
1825 protected void onUnhandledTap(MotionEvent ev) {}
1826
Winson Chung185d7162011-02-28 13:47:29 -08001827 @Override
1828 public boolean onGenericMotionEvent(MotionEvent event) {
1829 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1830 switch (event.getAction()) {
1831 case MotionEvent.ACTION_SCROLL: {
1832 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1833 final float vscroll;
1834 final float hscroll;
1835 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1836 vscroll = 0;
1837 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1838 } else {
1839 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1840 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1841 }
1842 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001843 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1844 : (hscroll > 0 || vscroll > 0);
1845 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001846 scrollRight();
1847 } else {
1848 scrollLeft();
1849 }
1850 return true;
1851 }
1852 }
1853 }
1854 }
1855 return super.onGenericMotionEvent(event);
1856 }
1857
Michael Jurkab8f06722010-10-10 15:58:46 -07001858 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1859 if (mVelocityTracker == null) {
1860 mVelocityTracker = VelocityTracker.obtain();
1861 }
1862 mVelocityTracker.addMovement(ev);
1863 }
1864
1865 private void releaseVelocityTracker() {
1866 if (mVelocityTracker != null) {
1867 mVelocityTracker.recycle();
1868 mVelocityTracker = null;
1869 }
1870 }
1871
Winson Chung321e9ee2010-08-09 13:37:56 -07001872 private void onSecondaryPointerUp(MotionEvent ev) {
1873 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1874 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1875 final int pointerId = ev.getPointerId(pointerIndex);
1876 if (pointerId == mActivePointerId) {
1877 // This was our active pointer going up. Choose a new
1878 // active pointer and adjust accordingly.
1879 // TODO: Make this decision more intelligent.
1880 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1881 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1882 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001883 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001884 mActivePointerId = ev.getPointerId(newPointerIndex);
1885 if (mVelocityTracker != null) {
1886 mVelocityTracker.clear();
1887 }
1888 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001889 }
1890
Winson Chung321e9ee2010-08-09 13:37:56 -07001891 @Override
1892 public void requestChildFocus(View child, View focused) {
1893 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001894 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001895 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001896 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001897 }
1898 }
1899
Winson Chung1908d072011-02-24 18:09:44 -08001900 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001901 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001902 }
1903
Adam Cohen7d30a372013-07-01 17:03:59 -07001904 int getPageNearestToPoint(float x) {
1905 int index = 0;
1906 for (int i = 0; i < getChildCount(); ++i) {
1907 if (x < getChildAt(i).getRight() - getScrollX()) {
1908 return index;
1909 } else {
1910 index++;
1911 }
1912 }
1913 return Math.min(index, getChildCount() - 1);
1914 }
1915
Adam Cohend19d3ca2010-09-15 14:43:42 -07001916 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001917 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001918 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001919 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001920 final int childCount = getChildCount();
1921 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001922 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001923 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001924 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001925 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001926 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1927 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1928 minDistanceFromScreenCenter = distanceFromScreenCenter;
1929 minDistanceFromScreenCenterIndex = i;
1930 }
1931 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001932 return minDistanceFromScreenCenterIndex;
1933 }
1934
1935 protected void snapToDestination() {
1936 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001937 }
1938
Adam Cohene0f66b52010-11-23 15:06:07 -08001939 private static class ScrollInterpolator implements Interpolator {
1940 public ScrollInterpolator() {
1941 }
1942
1943 public float getInterpolation(float t) {
1944 t -= 1.0f;
1945 return t*t*t*t*t + 1;
1946 }
1947 }
1948
1949 // We want the duration of the page snap animation to be influenced by the distance that
1950 // the screen has to travel, however, we don't want this duration to be effected in a
1951 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1952 // of travel has on the overall snap duration.
1953 float distanceInfluenceForSnapDuration(float f) {
1954 f -= 0.5f; // center the values about 0.
1955 f *= 0.3f * Math.PI / 2.0f;
1956 return (float) Math.sin(f);
1957 }
1958
Michael Jurka0142d492010-08-25 17:46:15 -07001959 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001960 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001961 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001962
Adam Cohenedb40762013-07-18 16:45:45 -07001963 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001964 int delta = newX - mUnboundedScrollX;
1965 int duration = 0;
1966
Adam Cohen265b9a62011-12-07 14:37:18 -08001967 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001968 // If the velocity is low enough, then treat this more as an automatic page advance
1969 // as opposed to an apparent physical response to flinging
1970 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1971 return;
1972 }
1973
1974 // Here we compute a "distance" that will be used in the computation of the overall
1975 // snap duration. This is a function of the actual distance that needs to be traveled;
1976 // we keep this value close to half screen size in order to reduce the variance in snap
1977 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001978 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001979 float distance = halfScreenSize + halfScreenSize *
1980 distanceInfluenceForSnapDuration(distanceRatio);
1981
1982 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001983 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001984
1985 // we want the page's snap velocity to approximately match the velocity at which the
1986 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001987 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1988 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001989
1990 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001991 }
1992
1993 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001994 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001995 }
1996
Adam Cohen7d30a372013-07-01 17:03:59 -07001997 protected void snapToPageImmediately(int whichPage) {
1998 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1999 }
2000
Michael Jurka0142d492010-08-25 17:46:15 -07002001 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 snapToPage(whichPage, duration, false);
2003 }
2004
2005 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07002006 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07002007
Adam Cohenedb40762013-07-18 16:45:45 -07002008 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002009 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002010 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002011 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002012 }
2013
2014 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002015 snapToPage(whichPage, delta, duration, false);
2016 }
Michael Jurka0142d492010-08-25 17:46:15 -07002017
Adam Cohen7d30a372013-07-01 17:03:59 -07002018 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2019 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002020 View focusedChild = getFocusedChild();
2021 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002022 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002023 focusedChild.clearFocus();
2024 }
2025
2026 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002027 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002028 if (immediate) {
2029 duration = 0;
2030 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002031 duration = Math.abs(delta);
2032 }
2033
2034 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002035 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002036
Michael Jurka0142d492010-08-25 17:46:15 -07002037 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002038
2039 // Trigger a compute() to finish switching pages if necessary
2040 if (immediate) {
2041 computeScroll();
2042 }
2043
Winson Chung9c0565f2013-07-19 13:49:06 -07002044 // Defer loading associated pages until the scroll settles
2045 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2046
Adam Cohen7d30a372013-07-01 17:03:59 -07002047 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002048 invalidate();
2049 }
2050
Winson Chung321e9ee2010-08-09 13:37:56 -07002051 public void scrollLeft() {
2052 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002053 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002054 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002055 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002056 }
2057 }
2058
2059 public void scrollRight() {
2060 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002061 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002062 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002063 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002064 }
2065 }
2066
Winson Chung86f77532010-08-24 11:08:22 -07002067 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002068 int result = -1;
2069 if (v != null) {
2070 ViewParent vp = v.getParent();
2071 int count = getChildCount();
2072 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002073 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002074 return i;
2075 }
2076 }
2077 }
2078 return result;
2079 }
2080
2081 /**
2082 * @return True is long presses are still allowed for the current touch
2083 */
2084 public boolean allowLongPress() {
2085 return mAllowLongPress;
2086 }
2087
Michael Jurka0142d492010-08-25 17:46:15 -07002088 /**
2089 * Set true to allow long-press events to be triggered, usually checked by
2090 * {@link Launcher} to accept or block dpad-initiated long-presses.
2091 */
2092 public void setAllowLongPress(boolean allowLongPress) {
2093 mAllowLongPress = allowLongPress;
2094 }
2095
Winson Chung321e9ee2010-08-09 13:37:56 -07002096 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002097 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002098
2099 SavedState(Parcelable superState) {
2100 super(superState);
2101 }
2102
2103 private SavedState(Parcel in) {
2104 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002105 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002106 }
2107
2108 @Override
2109 public void writeToParcel(Parcel out, int flags) {
2110 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002111 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002112 }
2113
2114 public static final Parcelable.Creator<SavedState> CREATOR =
2115 new Parcelable.Creator<SavedState>() {
2116 public SavedState createFromParcel(Parcel in) {
2117 return new SavedState(in);
2118 }
2119
2120 public SavedState[] newArray(int size) {
2121 return new SavedState[size];
2122 }
2123 };
2124 }
2125
Winson Chungf314b0e2011-08-16 11:54:27 -07002126 protected void loadAssociatedPages(int page) {
2127 loadAssociatedPages(page, false);
2128 }
2129 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002130 if (mContentIsRefreshable) {
2131 final int count = getChildCount();
2132 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002133 int lowerPageBound = getAssociatedLowerPageBound(page);
2134 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002135 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2136 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002137 // First, clear any pages that should no longer be loaded
2138 for (int i = 0; i < count; ++i) {
2139 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002140 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002141 if (layout.getPageChildCount() > 0) {
2142 layout.removeAllViewsOnPage();
2143 }
2144 mDirtyPageContent.set(i, true);
2145 }
2146 }
2147 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002148 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002149 if ((i != page) && immediateAndOnly) {
2150 continue;
2151 }
Michael Jurka0142d492010-08-25 17:46:15 -07002152 if (lowerPageBound <= i && i <= upperPageBound) {
2153 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002154 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002155 mDirtyPageContent.set(i, false);
2156 }
Winson Chung86f77532010-08-24 11:08:22 -07002157 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002158 }
2159 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002160 }
2161 }
2162
Winson Chunge3193b92010-09-10 11:44:42 -07002163 protected int getAssociatedLowerPageBound(int page) {
2164 return Math.max(0, page - 1);
2165 }
2166 protected int getAssociatedUpperPageBound(int page) {
2167 final int count = getChildCount();
2168 return Math.min(page + 1, count - 1);
2169 }
2170
Winson Chung86f77532010-08-24 11:08:22 -07002171 /**
2172 * This method is called ONLY to synchronize the number of pages that the paged view has.
2173 * To actually fill the pages with information, implement syncPageItems() below. It is
2174 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2175 * and therefore, individual page items do not need to be updated in this method.
2176 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002177 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002178
2179 /**
2180 * This method is called to synchronize the items that are on a particular page. If views on
2181 * the page can be reused, then they should be updated within this method.
2182 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002183 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002184
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002185 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002186 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002187 }
2188 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002189 invalidatePageData(currentPage, false);
2190 }
2191 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002192 if (!mIsDataReady) {
2193 return;
2194 }
2195
Michael Jurka0142d492010-08-25 17:46:15 -07002196 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002197 // Force all scrolling-related behavior to end
2198 mScroller.forceFinished(true);
2199 mNextPage = INVALID_PAGE;
2200
Michael Jurka0142d492010-08-25 17:46:15 -07002201 // Update all the pages
2202 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002203
Winson Chung5a808352011-06-27 19:08:49 -07002204 // We must force a measure after we've loaded the pages to update the content width and
2205 // to determine the full scroll width
2206 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2207 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2208
2209 // Set a new page as the current page if necessary
2210 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002211 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002212 }
2213
Michael Jurka0142d492010-08-25 17:46:15 -07002214 // Mark each of the pages as dirty
2215 final int count = getChildCount();
2216 mDirtyPageContent.clear();
2217 for (int i = 0; i < count; ++i) {
2218 mDirtyPageContent.add(true);
2219 }
2220
2221 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002222 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002223 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002224 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002225 }
Winson Chung007c6982011-06-14 13:27:53 -07002226
Adam Cohen7d30a372013-07-01 17:03:59 -07002227 // Animate the drag view back to the original position
2228 void animateDragViewToOriginalPosition() {
2229 if (mDragView != null) {
2230 AnimatorSet anim = new AnimatorSet();
2231 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2232 anim.playTogether(
2233 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2234 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2235 anim.addListener(new AnimatorListenerAdapter() {
2236 @Override
2237 public void onAnimationEnd(Animator animation) {
2238 onPostReorderingAnimationCompleted();
2239 }
2240 });
2241 anim.start();
2242 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002243 }
2244
Adam Cohen7d30a372013-07-01 17:03:59 -07002245 // "Zooms out" the PagedView to reveal more side pages
2246 protected boolean zoomOut() {
2247 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2248 mZoomInOutAnim.cancel();
2249 }
2250
2251 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2252 mZoomInOutAnim = new AnimatorSet();
2253 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2254 mZoomInOutAnim.playTogether(
2255 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2256 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2257 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2258 @Override
2259 public void onAnimationStart(Animator animation) {
2260 // Show the delete drop target
2261 if (mDeleteDropTarget != null) {
2262 mDeleteDropTarget.setVisibility(View.VISIBLE);
2263 mDeleteDropTarget.animate().alpha(1f)
2264 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2265 .setListener(new AnimatorListenerAdapter() {
2266 @Override
2267 public void onAnimationStart(Animator animation) {
2268 mDeleteDropTarget.setAlpha(0f);
2269 }
2270 });
2271 }
2272 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002273 @Override
2274 public void onAnimationEnd(Animator animation) {
2275 // Update the visible pages
2276 invalidate();
2277 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002278 });
2279 mZoomInOutAnim.start();
2280 return true;
2281 }
2282 return false;
2283 }
2284
2285 protected void onStartReordering() {
2286 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2287 mTouchState = TOUCH_STATE_REORDERING;
2288 mIsReordering = true;
2289
2290 // Mark all the non-widget pages as invisible
Winson Chungc9ca2982013-07-19 12:07:38 -07002291 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002292 for (int i = 0; i < getPageCount(); ++i) {
2293 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2294 getPageAt(i).setAlpha(0f);
2295 }
2296 }
2297
2298 // We must invalidate to trigger a redraw to update the layers such that the drag view
2299 // is always drawn on top
2300 invalidate();
2301 }
2302
2303 private void onPostReorderingAnimationCompleted() {
2304 // Trigger the callback when reordering has settled
2305 --mPostReorderingPreZoomInRemainingAnimationCount;
2306 if (mPostReorderingPreZoomInRunnable != null &&
2307 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2308 mPostReorderingPreZoomInRunnable.run();
2309 mPostReorderingPreZoomInRunnable = null;
2310 }
2311 }
2312
2313 protected void onEndReordering() {
2314 mIsReordering = false;
2315
2316 // Mark all the non-widget pages as visible again
Winson Chungc9ca2982013-07-19 12:07:38 -07002317 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002318 for (int i = 0; i < getPageCount(); ++i) {
2319 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2320 getPageAt(i).setAlpha(1f);
2321 }
2322 }
2323 }
2324
2325 public boolean startReordering() {
2326 int dragViewIndex = getPageNearestToCenterOfScreen();
2327 mTempVisiblePagesRange[0] = 0;
2328 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07002329 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002330 mReorderingStarted = true;
2331
2332 // Check if we are within the reordering range
2333 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2334 dragViewIndex <= mTempVisiblePagesRange[1]) {
2335 if (zoomOut()) {
2336 // Find the drag view under the pointer
2337 mDragView = getChildAt(dragViewIndex);
2338
2339 onStartReordering();
2340 }
2341 return true;
2342 }
2343 return false;
2344 }
2345
2346 boolean isReordering(boolean testTouchState) {
2347 boolean state = mIsReordering;
2348 if (testTouchState) {
2349 state &= (mTouchState == TOUCH_STATE_REORDERING);
2350 }
2351 return state;
2352 }
2353 void endReordering() {
2354 // For simplicity, we call endReordering sometimes even if reordering was never started.
2355 // In that case, we don't want to do anything.
2356 if (!mReorderingStarted) return;
2357 mReorderingStarted = false;
2358
2359 // If we haven't flung-to-delete the current child, then we just animate the drag view
2360 // back into position
2361 final Runnable onCompleteRunnable = new Runnable() {
2362 @Override
2363 public void run() {
2364 onEndReordering();
2365 }
2366 };
2367 if (!mDeferringForDelete) {
2368 mPostReorderingPreZoomInRunnable = new Runnable() {
2369 public void run() {
2370 zoomIn(onCompleteRunnable);
2371 };
2372 };
2373
2374 mPostReorderingPreZoomInRemainingAnimationCount =
2375 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2376 // Snap to the current page
2377 snapToPage(indexOfChild(mDragView), 0);
2378 // Animate the drag view back to the front position
2379 animateDragViewToOriginalPosition();
2380 } else {
2381 // Handled in post-delete-animation-callbacks
2382 }
2383 }
2384
2385 // "Zooms in" the PagedView to highlight the current page
2386 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2387 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2388 mZoomInOutAnim.cancel();
2389 }
2390 if (getScaleX() < 1f || getScaleY() < 1f) {
2391 mZoomInOutAnim = new AnimatorSet();
2392 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2393 mZoomInOutAnim.playTogether(
2394 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2395 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2396 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2397 @Override
2398 public void onAnimationStart(Animator animation) {
2399 // Hide the delete drop target
2400 if (mDeleteDropTarget != null) {
2401 mDeleteDropTarget.animate().alpha(0f)
2402 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2403 .setListener(new AnimatorListenerAdapter() {
2404 @Override
2405 public void onAnimationEnd(Animator animation) {
2406 mDeleteDropTarget.setVisibility(View.GONE);
2407 }
2408 });
2409 }
2410 }
2411 @Override
2412 public void onAnimationCancel(Animator animation) {
2413 mDragView = null;
2414 }
2415 @Override
2416 public void onAnimationEnd(Animator animation) {
2417 mDragView = null;
2418 if (onCompleteRunnable != null) {
2419 onCompleteRunnable.run();
2420 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002421 // Update the visible pages
2422 invalidate();
Adam Cohen7d30a372013-07-01 17:03:59 -07002423 }
2424 });
2425 mZoomInOutAnim.start();
2426 return true;
2427 } else {
2428 if (onCompleteRunnable != null) {
2429 onCompleteRunnable.run();
2430 }
2431 }
2432 return false;
2433 }
2434
2435 /*
2436 * Flinging to delete - IN PROGRESS
2437 */
2438 private PointF isFlingingToDelete() {
2439 ViewConfiguration config = ViewConfiguration.get(getContext());
2440 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2441
2442 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2443 // Do a quick dot product test to ensure that we are flinging upwards
2444 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2445 mVelocityTracker.getYVelocity());
2446 PointF upVec = new PointF(0f, -1f);
2447 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2448 (vel.length() * upVec.length()));
2449 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2450 return vel;
2451 }
2452 }
2453 return null;
2454 }
2455
2456 /**
2457 * Creates an animation from the current drag view along its current velocity vector.
2458 * For this animation, the alpha runs for a fixed duration and we update the position
2459 * progressively.
2460 */
2461 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2462 private View mDragView;
2463 private PointF mVelocity;
2464 private Rect mFrom;
2465 private long mPrevTime;
2466 private float mFriction;
2467
2468 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2469
2470 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2471 long startTime, float friction) {
2472 mDragView = dragView;
2473 mVelocity = vel;
2474 mFrom = from;
2475 mPrevTime = startTime;
2476 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2477 }
2478
2479 @Override
2480 public void onAnimationUpdate(ValueAnimator animation) {
2481 float t = ((Float) animation.getAnimatedValue()).floatValue();
2482 long curTime = AnimationUtils.currentAnimationTimeMillis();
2483
2484 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2485 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2486
2487 mDragView.setTranslationX(mFrom.left);
2488 mDragView.setTranslationY(mFrom.top);
2489 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2490
2491 mVelocity.x *= mFriction;
2492 mVelocity.y *= mFriction;
2493 mPrevTime = curTime;
2494 }
2495 };
2496
2497 private static final int ANIM_TAG_KEY = 100;
2498
2499 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2500 return new Runnable() {
2501 @Override
2502 public void run() {
2503 int dragViewIndex = indexOfChild(dragView);
2504
2505 // For each of the pages around the drag view, animate them from the previous
2506 // position to the new position in the layout (as a result of the drag view moving
2507 // in the layout)
2508 // NOTE: We can make an assumption here because we have side-bound pages that we
2509 // will always have pages to animate in from the left
Winson Chungc9ca2982013-07-19 12:07:38 -07002510 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002511 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2512 boolean slideFromLeft = (isLastWidgetPage ||
2513 dragViewIndex > mTempVisiblePagesRange[0]);
2514
2515 // Setup the scroll to the correct page before we swap the views
2516 if (slideFromLeft) {
2517 snapToPageImmediately(dragViewIndex - 1);
2518 }
2519
2520 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2521 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2522 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2523 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2524 ArrayList<Animator> animations = new ArrayList<Animator>();
2525 for (int i = lowerIndex; i <= upperIndex; ++i) {
2526 View v = getChildAt(i);
2527 // dragViewIndex < pageUnderPointIndex, so after we remove the
2528 // drag view all subsequent views to pageUnderPointIndex will
2529 // shift down.
2530 int oldX = 0;
2531 int newX = 0;
2532 if (slideFromLeft) {
2533 if (i == 0) {
2534 // Simulate the page being offscreen with the page spacing
2535 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2536 - mPageSpacing;
2537 } else {
2538 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2539 }
2540 newX = getViewportOffsetX() + getChildOffset(i);
2541 } else {
2542 oldX = getChildOffset(i) - getChildOffset(i - 1);
2543 newX = 0;
2544 }
2545
2546 // Animate the view translation from its old position to its new
2547 // position
2548 AnimatorSet anim = (AnimatorSet) v.getTag();
2549 if (anim != null) {
2550 anim.cancel();
2551 }
2552
2553 // Note: Hacky, but we want to skip any optimizations to not draw completely
2554 // hidden views
2555 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2556 v.setTranslationX(oldX - newX);
2557 anim = new AnimatorSet();
2558 anim.playTogether(
2559 ObjectAnimator.ofFloat(v, "translationX", 0f),
2560 ObjectAnimator.ofFloat(v, "alpha", 1f));
2561 animations.add(anim);
2562 v.setTag(ANIM_TAG_KEY, anim);
2563 }
2564
2565 AnimatorSet slideAnimations = new AnimatorSet();
2566 slideAnimations.playTogether(animations);
2567 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2568 slideAnimations.addListener(new AnimatorListenerAdapter() {
2569 @Override
2570 public void onAnimationEnd(Animator animation) {
2571 final Runnable onCompleteRunnable = new Runnable() {
2572 @Override
2573 public void run() {
2574 mDeferringForDelete = false;
2575 onEndReordering();
2576 onRemoveViewAnimationCompleted();
2577 }
2578 };
2579 zoomIn(onCompleteRunnable);
2580 }
2581 });
2582 slideAnimations.start();
2583
2584 removeView(dragView);
2585 onRemoveView(dragView, true);
2586 }
2587 };
2588 }
2589
2590 public void onFlingToDelete(PointF vel) {
2591 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2592
2593 // NOTE: Because it takes time for the first frame of animation to actually be
2594 // called and we expect the animation to be a continuation of the fling, we have
2595 // to account for the time that has elapsed since the fling finished. And since
2596 // we don't have a startDelay, we will always get call to update when we call
2597 // start() (which we want to ignore).
2598 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2599 private int mCount = -1;
2600 private long mStartTime;
2601 private float mOffset;
2602 /* Anonymous inner class ctor */ {
2603 mStartTime = startTime;
2604 }
2605
2606 @Override
2607 public float getInterpolation(float t) {
2608 if (mCount < 0) {
2609 mCount++;
2610 } else if (mCount == 0) {
2611 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2612 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2613 mCount++;
2614 }
2615 return Math.min(1f, mOffset + t);
2616 }
2617 };
2618
2619 final Rect from = new Rect();
2620 final View dragView = mDragView;
2621 from.left = (int) dragView.getTranslationX();
2622 from.top = (int) dragView.getTranslationY();
2623 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2624 from, startTime, FLING_TO_DELETE_FRICTION);
2625
2626 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2627
2628 // Create and start the animation
2629 ValueAnimator mDropAnim = new ValueAnimator();
2630 mDropAnim.setInterpolator(tInterpolator);
2631 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2632 mDropAnim.setFloatValues(0f, 1f);
2633 mDropAnim.addUpdateListener(updateCb);
2634 mDropAnim.addListener(new AnimatorListenerAdapter() {
2635 public void onAnimationEnd(Animator animation) {
2636 onAnimationEndRunnable.run();
2637 }
2638 });
2639 mDropAnim.start();
2640 mDeferringForDelete = true;
2641 }
2642
2643 /* Drag to delete */
2644 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2645 if (mDeleteDropTarget != null) {
2646 mAltTmpRect.set(0, 0, 0, 0);
2647 View parent = (View) mDeleteDropTarget.getParent();
2648 if (parent != null) {
2649 parent.getGlobalVisibleRect(mAltTmpRect);
2650 }
2651 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2652 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2653 return mTmpRect.contains(x, y);
2654 }
2655 return false;
2656 }
2657
2658 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2659
2660 private void onDropToDelete() {
2661 final View dragView = mDragView;
2662
2663 final float toScale = 0f;
2664 final float toAlpha = 0f;
2665
2666 // Create and start the complex animation
2667 ArrayList<Animator> animations = new ArrayList<Animator>();
2668 AnimatorSet motionAnim = new AnimatorSet();
2669 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2670 motionAnim.playTogether(
2671 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2672 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2673 animations.add(motionAnim);
2674
2675 AnimatorSet alphaAnim = new AnimatorSet();
2676 alphaAnim.setInterpolator(new LinearInterpolator());
2677 alphaAnim.playTogether(
2678 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2679 animations.add(alphaAnim);
2680
2681 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2682
2683 AnimatorSet anim = new AnimatorSet();
2684 anim.playTogether(animations);
2685 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2686 anim.addListener(new AnimatorListenerAdapter() {
2687 public void onAnimationEnd(Animator animation) {
2688 onAnimationEndRunnable.run();
2689 }
2690 });
2691 anim.start();
2692
2693 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002694 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002695
2696 /* Accessibility */
2697 @Override
2698 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2699 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002700 info.setScrollable(getPageCount() > 1);
2701 if (getCurrentPage() < getPageCount() - 1) {
2702 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2703 }
2704 if (getCurrentPage() > 0) {
2705 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2706 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002707 }
2708
2709 @Override
2710 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2711 super.onInitializeAccessibilityEvent(event);
2712 event.setScrollable(true);
2713 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2714 event.setFromIndex(mCurrentPage);
2715 event.setToIndex(mCurrentPage);
2716 event.setItemCount(getChildCount());
2717 }
2718 }
2719
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002720 @Override
2721 public boolean performAccessibilityAction(int action, Bundle arguments) {
2722 if (super.performAccessibilityAction(action, arguments)) {
2723 return true;
2724 }
2725 switch (action) {
2726 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2727 if (getCurrentPage() < getPageCount() - 1) {
2728 scrollRight();
2729 return true;
2730 }
2731 } break;
2732 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2733 if (getCurrentPage() > 0) {
2734 scrollLeft();
2735 return true;
2736 }
2737 } break;
2738 }
2739 return false;
2740 }
2741
Adam Cohen0ffac432013-07-10 11:19:26 -07002742 protected String getCurrentPageDescription() {
2743 return String.format(getContext().getString(R.string.default_scroll_format),
2744 getNextPage() + 1, getChildCount());
2745 }
2746
Winson Chungd11265e2011-08-30 13:37:23 -07002747 @Override
2748 public boolean onHoverEvent(android.view.MotionEvent event) {
2749 return true;
2750 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002751}