blob: 9a851ac368a503eea8b70fcc664641a7b623f379 [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();
330 mPageIndicator.addMarkers(getChildCount());
331 }
332 }
333
334 protected void onDetachedFromWindow() {
335 // Unhook the page indicator
336 mPageIndicator = null;
337 }
338
Adam Cohen7d30a372013-07-01 17:03:59 -0700339 void setDeleteDropTarget(View v) {
340 mDeleteDropTarget = v;
341 }
342
343 // Convenience methods to map points from self to parent and vice versa
344 float[] mapPointFromViewToParent(View v, float x, float y) {
345 mTmpPoint[0] = x;
346 mTmpPoint[1] = y;
347 v.getMatrix().mapPoints(mTmpPoint);
348 mTmpPoint[0] += v.getLeft();
349 mTmpPoint[1] += v.getTop();
350 return mTmpPoint;
351 }
352 float[] mapPointFromParentToView(View v, float x, float y) {
353 mTmpPoint[0] = x - v.getLeft();
354 mTmpPoint[1] = y - v.getTop();
355 v.getMatrix().invert(mTmpInvMatrix);
356 mTmpInvMatrix.mapPoints(mTmpPoint);
357 return mTmpPoint;
358 }
359
360 void updateDragViewTranslationDuringDrag() {
361 float x = mLastMotionX - mDownMotionX + getScrollX() - mDownScrollX;
362 float y = mLastMotionY - mDownMotionY;
363 mDragView.setTranslationX(x);
364 mDragView.setTranslationY(y);
365
366 if (DEBUG) Log.d(TAG, "PagedView.updateDragViewTranslationDuringDrag(): " + x + ", " + y);
367 }
368
369 public void setMinScale(float f) {
370 mMinScale = f;
371 requestLayout();
372 }
373
374 @Override
375 public void setScaleX(float scaleX) {
376 super.setScaleX(scaleX);
377 if (isReordering(true)) {
378 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
379 mLastMotionX = p[0];
380 mLastMotionY = p[1];
381 updateDragViewTranslationDuringDrag();
382 }
383 }
384
385 // Convenience methods to get the actual width/height of the PagedView (since it is measured
386 // to be larger to account for the minimum possible scale)
387 int getViewportWidth() {
388 return mViewport.width();
389 }
390 int getViewportHeight() {
391 return mViewport.height();
392 }
393
394 // Convenience methods to get the offset ASSUMING that we are centering the pages in the
395 // PagedView both horizontally and vertically
396 int getViewportOffsetX() {
397 return (getMeasuredWidth() - getViewportWidth()) / 2;
398 }
399
400 int getViewportOffsetY() {
401 return (getMeasuredHeight() - getViewportHeight()) / 2;
402 }
403
Adam Cohenedb40762013-07-18 16:45:45 -0700404 PageIndicator getPageIndicator() {
405 return mPageIndicator;
406 }
407
Winson Chung86f77532010-08-24 11:08:22 -0700408 public void setPageSwitchListener(PageSwitchListener pageSwitchListener) {
409 mPageSwitchListener = pageSwitchListener;
410 if (mPageSwitchListener != null) {
411 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700412 }
413 }
414
415 /**
Winson Chung52aee602013-01-30 12:01:02 -0800416 * Note: this is a reimplementation of View.isLayoutRtl() since that is currently hidden api.
417 */
418 public boolean isLayoutRtl() {
419 return (getLayoutDirection() == LAYOUT_DIRECTION_RTL);
420 }
421
422 /**
Winson Chungf0ea4d32011-06-06 14:27:16 -0700423 * Called by subclasses to mark that data is ready, and that we can begin loading and laying
424 * out pages.
425 */
426 protected void setDataIsReady() {
427 mIsDataReady = true;
428 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700429
Winson Chungf0ea4d32011-06-06 14:27:16 -0700430 protected boolean isDataReady() {
431 return mIsDataReady;
432 }
433
434 /**
Winson Chung86f77532010-08-24 11:08:22 -0700435 * Returns the index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700436 *
Winson Chung86f77532010-08-24 11:08:22 -0700437 * @return The index of the currently displayed page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700438 */
Winson Chung86f77532010-08-24 11:08:22 -0700439 int getCurrentPage() {
440 return mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -0700441 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700442
Winson Chung360e63f2012-04-27 13:48:05 -0700443 int getNextPage() {
444 return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage;
445 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700446
Winson Chung86f77532010-08-24 11:08:22 -0700447 int getPageCount() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700448 return getChildCount();
449 }
450
Winson Chung86f77532010-08-24 11:08:22 -0700451 View getPageAt(int index) {
Winson Chung321e9ee2010-08-09 13:37:56 -0700452 return getChildAt(index);
453 }
454
Adam Cohenae4f1552011-10-20 00:15:42 -0700455 protected int indexToPage(int index) {
456 return index;
457 }
458
Winson Chung321e9ee2010-08-09 13:37:56 -0700459 /**
Winson Chungbbc60d82010-11-11 16:34:41 -0800460 * Updates the scroll of the current page immediately to its final scroll position. We use this
461 * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of
462 * the previous tab page.
463 */
464 protected void updateCurrentPageScroll() {
Adam Cohen0ffac432013-07-10 11:19:26 -0700465 // If the current page is invalid, just reset the scroll position to zero
466 int newX = 0;
467 if (0 <= mCurrentPage && mCurrentPage < getPageCount()) {
Adam Cohenedb40762013-07-18 16:45:45 -0700468 newX = getScrollForPage(mCurrentPage);
Adam Cohen0ffac432013-07-10 11:19:26 -0700469 }
Winson Chungbbc60d82010-11-11 16:34:41 -0800470 scrollTo(newX, 0);
471 mScroller.setFinalX(newX);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800472 mScroller.forceFinished(true);
Winson Chungbbc60d82010-11-11 16:34:41 -0800473 }
474
475 /**
Chet Haasebc2f0822012-10-26 17:59:53 -0700476 * Called during AllApps/Home transitions to avoid unnecessary work. When that other animation
477 * ends, {@link #resumeScrolling()} should be called, along with
478 * {@link #updateCurrentPageScroll()} to correctly set the final state and re-enable scrolling.
479 */
480 void pauseScrolling() {
481 mScroller.forceFinished(true);
Chet Haasebc2f0822012-10-26 17:59:53 -0700482 }
483
484 /**
485 * Enables scrolling again.
486 * @see #pauseScrolling()
487 */
488 void resumeScrolling() {
Chet Haasebc2f0822012-10-26 17:59:53 -0700489 }
490 /**
Winson Chung86f77532010-08-24 11:08:22 -0700491 * Sets the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -0700492 */
Winson Chung86f77532010-08-24 11:08:22 -0700493 void setCurrentPage(int currentPage) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800494 if (!mScroller.isFinished()) {
495 mScroller.abortAnimation();
496 }
Michael Jurkad3ef3062010-11-23 16:23:58 -0800497 // don't introduce any checks like mCurrentPage == currentPage here-- if we change the
498 // the default
499 if (getChildCount() == 0) {
Patrick Dubroy72e0d342010-11-09 15:23:28 -0800500 return;
501 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700502
Adam Cohene61a9a22013-06-11 15:45:31 -0700503 mForceScreenScrolled = true;
Winson Chung86f77532010-08-24 11:08:22 -0700504 mCurrentPage = Math.max(0, Math.min(currentPage, getPageCount() - 1));
Winson Chung181c3dc2013-07-17 15:36:20 -0700505 updateCurrentPageScroll();
Winson Chung86f77532010-08-24 11:08:22 -0700506 notifyPageSwitchListener();
Winson Chunga12a2502010-12-20 14:41:35 -0800507 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -0700508 }
509
Winson Chung8c87cd82013-07-23 16:20:10 -0700510 /**
511 * The restore page will be set in place of the current page at the next (likely first)
512 * layout.
513 */
514 void setRestorePage(int restorePage) {
515 mRestorePage = restorePage;
516 }
517
Michael Jurka0142d492010-08-25 17:46:15 -0700518 protected void notifyPageSwitchListener() {
Winson Chung86f77532010-08-24 11:08:22 -0700519 if (mPageSwitchListener != null) {
520 mPageSwitchListener.onPageSwitch(getPageAt(mCurrentPage), mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -0700521 }
Winson Chungd2be3812013-07-16 11:11:32 -0700522
523 // Update the page indicator (when we aren't reordering)
524 if (mPageIndicator != null && !isReordering(false)) {
525 mPageIndicator.setActiveMarker(getNextPage());
526 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700527 }
Michael Jurkace7e05f2011-02-01 22:02:35 -0800528 protected void pageBeginMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700529 if (!mIsPageMoving) {
530 mIsPageMoving = true;
531 onPageBeginMoving();
532 }
Patrick Dubroy1262e362010-10-06 15:49:50 -0700533 }
534
Michael Jurkace7e05f2011-02-01 22:02:35 -0800535 protected void pageEndMoving() {
Michael Jurkad74c9842011-07-10 12:44:21 -0700536 if (mIsPageMoving) {
537 mIsPageMoving = false;
538 onPageEndMoving();
539 }
Michael Jurka0142d492010-08-25 17:46:15 -0700540 }
541
Adam Cohen26976d92011-03-22 15:33:33 -0700542 protected boolean isPageMoving() {
543 return mIsPageMoving;
544 }
545
Michael Jurka0142d492010-08-25 17:46:15 -0700546 // a method that subclasses can override to add behavior
Patrick Dubroy1262e362010-10-06 15:49:50 -0700547 protected void onPageBeginMoving() {
548 }
549
550 // a method that subclasses can override to add behavior
551 protected void onPageEndMoving() {
Michael Jurka0142d492010-08-25 17:46:15 -0700552 }
553
Winson Chung321e9ee2010-08-09 13:37:56 -0700554 /**
Winson Chung86f77532010-08-24 11:08:22 -0700555 * Registers the specified listener on each page contained in this workspace.
Winson Chung321e9ee2010-08-09 13:37:56 -0700556 *
557 * @param l The listener used to respond to long clicks.
558 */
559 @Override
560 public void setOnLongClickListener(OnLongClickListener l) {
561 mLongClickListener = l;
Winson Chung86f77532010-08-24 11:08:22 -0700562 final int count = getPageCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700563 for (int i = 0; i < count; i++) {
Winson Chung86f77532010-08-24 11:08:22 -0700564 getPageAt(i).setOnLongClickListener(l);
Winson Chung321e9ee2010-08-09 13:37:56 -0700565 }
566 }
567
568 @Override
Adam Cohen68d73932010-11-15 10:50:58 -0800569 public void scrollBy(int x, int y) {
Michael Jurka8b805b12012-04-18 14:23:14 -0700570 scrollTo(mUnboundedScrollX + x, getScrollY() + y);
Adam Cohen68d73932010-11-15 10:50:58 -0800571 }
572
573 @Override
Michael Jurka0142d492010-08-25 17:46:15 -0700574 public void scrollTo(int x, int y) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700575 final boolean isRtl = isLayoutRtl();
Adam Cohen68d73932010-11-15 10:50:58 -0800576 mUnboundedScrollX = x;
577
Adam Cohen0ffac432013-07-10 11:19:26 -0700578 boolean isXBeforeFirstPage = isRtl ? (x > mMaxScrollX) : (x < 0);
579 boolean isXAfterLastPage = isRtl ? (x < 0) : (x > mMaxScrollX);
580 if (isXBeforeFirstPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800581 super.scrollTo(0, y);
582 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700583 if (isRtl) {
584 overScroll(x - mMaxScrollX);
585 } else {
586 overScroll(x);
587 }
Adam Cohen68d73932010-11-15 10:50:58 -0800588 }
Adam Cohen0ffac432013-07-10 11:19:26 -0700589 } else if (isXAfterLastPage) {
Adam Cohen68d73932010-11-15 10:50:58 -0800590 super.scrollTo(mMaxScrollX, y);
591 if (mAllowOverScroll) {
Adam Cohen0ffac432013-07-10 11:19:26 -0700592 if (isRtl) {
593 overScroll(x);
594 } else {
595 overScroll(x - mMaxScrollX);
596 }
Adam Cohen68d73932010-11-15 10:50:58 -0800597 }
598 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -0800599 mOverScrollX = x;
Adam Cohen68d73932010-11-15 10:50:58 -0800600 super.scrollTo(x, y);
601 }
602
Michael Jurka0142d492010-08-25 17:46:15 -0700603 mTouchX = x;
604 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
Adam Cohen7d30a372013-07-01 17:03:59 -0700605
606 // Update the last motion events when scrolling
607 if (isReordering(true)) {
608 float[] p = mapPointFromParentToView(this, mParentDownMotionX, mParentDownMotionY);
609 mLastMotionX = p[0];
610 mLastMotionY = p[1];
611 updateDragViewTranslationDuringDrag();
612 }
Michael Jurka0142d492010-08-25 17:46:15 -0700613 }
614
615 // we moved this functionality to a helper function so SmoothPagedView can reuse it
616 protected boolean computeScrollHelper() {
Winson Chung321e9ee2010-08-09 13:37:56 -0700617 if (mScroller.computeScrollOffset()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700618 // Don't bother scrolling if the page does not need to be moved
Michael Jurka8b805b12012-04-18 14:23:14 -0700619 if (getScrollX() != mScroller.getCurrX()
620 || getScrollY() != mScroller.getCurrY()
Michael Jurkab06d95f2012-04-02 06:26:53 -0700621 || mOverScrollX != mScroller.getCurrX()) {
Winson Chung557d6ed2011-07-08 15:34:52 -0700622 scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
623 }
Michael Jurka0142d492010-08-25 17:46:15 -0700624 invalidate();
625 return true;
Winson Chung86f77532010-08-24 11:08:22 -0700626 } else if (mNextPage != INVALID_PAGE) {
627 mCurrentPage = Math.max(0, Math.min(mNextPage, getPageCount() - 1));
Winson Chung86f77532010-08-24 11:08:22 -0700628 mNextPage = INVALID_PAGE;
Michael Jurka0142d492010-08-25 17:46:15 -0700629 notifyPageSwitchListener();
Winson Chungb44b5242011-06-13 11:32:14 -0700630
Winson Chung9c0565f2013-07-19 13:49:06 -0700631 // Load the associated pages if necessary
632 if (mDeferLoadAssociatedPagesUntilScrollCompletes) {
633 loadAssociatedPages(mCurrentPage);
634 mDeferLoadAssociatedPagesUntilScrollCompletes = false;
635 }
636
Adam Cohen73aa9752010-11-24 16:26:58 -0800637 // We don't want to trigger a page end moving unless the page has settled
638 // and the user has stopped scrolling
639 if (mTouchState == TOUCH_STATE_REST) {
640 pageEndMoving();
641 }
Winson Chungc27d1bb2011-09-29 12:07:42 -0700642
Adam Cohen7d30a372013-07-01 17:03:59 -0700643 onPostReorderingAnimationCompleted();
Adam Cohen0ffac432013-07-10 11:19:26 -0700644 // Notify the user when the page changes
645 AccessibilityManager accessibilityManager = (AccessibilityManager)
646 getContext().getSystemService(Context.ACCESSIBILITY_SERVICE);
647 if (accessibilityManager.isEnabled()) {
648 AccessibilityEvent ev =
649 AccessibilityEvent.obtain(AccessibilityEvent.TYPE_VIEW_SCROLLED);
650 ev.getText().add(getCurrentPageDescription());
651 sendAccessibilityEventUnchecked(ev);
652 }
Michael Jurka0142d492010-08-25 17:46:15 -0700653 return true;
Winson Chung321e9ee2010-08-09 13:37:56 -0700654 }
Michael Jurka0142d492010-08-25 17:46:15 -0700655 return false;
656 }
657
658 @Override
659 public void computeScroll() {
660 computeScrollHelper();
Winson Chung321e9ee2010-08-09 13:37:56 -0700661 }
662
Adam Cohen7d30a372013-07-01 17:03:59 -0700663 protected boolean shouldSetTopAlignedPivotForWidget(int childIndex) {
664 return mTopAlignPageWhenShrinkingForBouncer;
665 }
666
Adam Cohen96d30a12013-07-16 18:13:21 -0700667 public static class LayoutParams extends ViewGroup.LayoutParams {
668 public boolean isFullScreenPage = false;
669
670 /**
671 * {@inheritDoc}
672 */
673 public LayoutParams(int width, int height) {
674 super(width, height);
675 }
676
677 public LayoutParams(ViewGroup.LayoutParams source) {
678 super(source);
679 }
680 }
681
682 protected LayoutParams generateDefaultLayoutParams() {
683 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
684 }
685
Adam Cohenedb40762013-07-18 16:45:45 -0700686 public void addFullScreenPage(View page) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700687 LayoutParams lp = generateDefaultLayoutParams();
688 lp.isFullScreenPage = true;
689 super.addView(page, 0, lp);
690 }
691
Winson Chung321e9ee2010-08-09 13:37:56 -0700692 @Override
693 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700694 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700695 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
696 return;
697 }
698
Adam Cohen7d30a372013-07-01 17:03:59 -0700699 // We measure the dimensions of the PagedView to be larger than the pages so that when we
700 // zoom out (and scale down), the view is still contained in the parent
Adam Cohen7d30a372013-07-01 17:03:59 -0700701 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
702 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
703 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
Winson Chung8aad6102012-05-11 16:27:49 -0700704 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
Adam Cohen7d30a372013-07-01 17:03:59 -0700705 // NOTE: We multiply by 1.5f to account for the fact that depending on the offset of the
706 // viewport, we can be at most one and a half screens offset once we scale down
707 DisplayMetrics dm = getResources().getDisplayMetrics();
708 int maxSize = Math.max(dm.widthPixels, dm.heightPixels);
709 int parentWidthSize = (int) (1.5f * maxSize);
710 int parentHeightSize = maxSize;
711 int scaledWidthSize = (int) (parentWidthSize / mMinScale);
712 int scaledHeightSize = (int) (parentHeightSize / mMinScale);
713 mViewport.set(0, 0, widthSize, heightSize);
714
715 if (widthMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.UNSPECIFIED) {
716 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
717 return;
Winson Chung321e9ee2010-08-09 13:37:56 -0700718 }
719
Winson Chung8aad6102012-05-11 16:27:49 -0700720 // Return early if we aren't given a proper dimension
721 if (widthSize <= 0 || heightSize <= 0) {
722 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
723 return;
724 }
725
Adam Lesinski6b879f02010-11-04 16:15:23 -0700726 /* Allow the height to be set as WRAP_CONTENT. This allows the particular case
727 * of the All apps view on XLarge displays to not take up more space then it needs. Width
728 * is still not allowed to be set as WRAP_CONTENT since many parts of the code expect
729 * each page to have the same width.
730 */
Michael Jurka8b805b12012-04-18 14:23:14 -0700731 final int verticalPadding = getPaddingTop() + getPaddingBottom();
732 final int horizontalPadding = getPaddingLeft() + getPaddingRight();
Winson Chung321e9ee2010-08-09 13:37:56 -0700733
734 // The children are given the same width and height as the workspace
Michael Jurka5f1c5092010-09-03 14:15:02 -0700735 // unless they were set to WRAP_CONTENT
Winson Chung785d2eb2011-04-14 16:08:02 -0700736 if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize);
Adam Cohen7d30a372013-07-01 17:03:59 -0700737 if (DEBUG) Log.d(TAG, "PagedView.scaledSize: " + scaledWidthSize + ", " + scaledHeightSize);
738 if (DEBUG) Log.d(TAG, "PagedView.parentSize: " + parentWidthSize + ", " + parentHeightSize);
739 if (DEBUG) Log.d(TAG, "PagedView.horizontalPadding: " + horizontalPadding);
740 if (DEBUG) Log.d(TAG, "PagedView.verticalPadding: " + verticalPadding);
Winson Chung321e9ee2010-08-09 13:37:56 -0700741 final int childCount = getChildCount();
742 for (int i = 0; i < childCount; i++) {
Michael Jurka5f1c5092010-09-03 14:15:02 -0700743 // disallowing padding in paged view (just pass 0)
Adam Cohen22f823d2011-09-01 17:22:18 -0700744 final View child = getPageAt(i);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700745 final LayoutParams lp = (LayoutParams) child.getLayoutParams();
746
747 int childWidthMode;
Adam Cohen96d30a12013-07-16 18:13:21 -0700748 int childHeightMode;
749 int childWidth;
750 int childHeight;
751
752 if (!lp.isFullScreenPage) {
753 if (lp.width == LayoutParams.WRAP_CONTENT) {
754 childWidthMode = MeasureSpec.AT_MOST;
755 } else {
756 childWidthMode = MeasureSpec.EXACTLY;
757 }
758
759 if (lp.height == LayoutParams.WRAP_CONTENT) {
760 childHeightMode = MeasureSpec.AT_MOST;
761 } else {
762 childHeightMode = MeasureSpec.EXACTLY;
763 }
764
765 childWidth = widthSize - horizontalPadding;
766 childHeight = heightSize - verticalPadding;
767
Michael Jurka5f1c5092010-09-03 14:15:02 -0700768 } else {
769 childWidthMode = MeasureSpec.EXACTLY;
Michael Jurka5f1c5092010-09-03 14:15:02 -0700770 childHeightMode = MeasureSpec.EXACTLY;
Adam Cohen96d30a12013-07-16 18:13:21 -0700771
772 childWidth = getViewportWidth();
773 childHeight = getViewportHeight();
Michael Jurka5f1c5092010-09-03 14:15:02 -0700774 }
775
776 final int childWidthMeasureSpec =
Adam Cohen96d30a12013-07-16 18:13:21 -0700777 MeasureSpec.makeMeasureSpec(childWidth, childWidthMode);
778 final int childHeightMeasureSpec =
779 MeasureSpec.makeMeasureSpec(childHeight, childHeightMode);
Michael Jurka5f1c5092010-09-03 14:15:02 -0700780 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700781 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700782 setMeasuredDimension(scaledWidthSize, scaledHeightSize);
Winson Chungae890b82011-09-13 18:08:54 -0700783
Winson Chunga128a7b2012-04-30 15:23:15 -0700784 if (childCount > 0) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700785 // Calculate the variable page spacing if necessary
Adam Cohen7d30a372013-07-01 17:03:59 -0700786 if (mAutoComputePageSpacing && mRecomputePageSpacing) {
Winson Chunga128a7b2012-04-30 15:23:15 -0700787 // The gap between pages in the PagedView should be equal to the gap from the page
788 // to the edge of the screen (so it is not visible in the current screen). To
789 // account for unequal padding on each side of the paged view, we take the maximum
790 // of the left/right gap and use that as the gap between each page.
Adam Cohenedb40762013-07-18 16:45:45 -0700791 int offset = (getViewportWidth() - getChildWidth(0)) / 2;
Winson Chunga128a7b2012-04-30 15:23:15 -0700792 int spacing = Math.max(offset, widthSize - offset -
793 getChildAt(0).getMeasuredWidth());
794 setPageSpacing(spacing);
Adam Cohen7d30a372013-07-01 17:03:59 -0700795 mRecomputePageSpacing = false;
Winson Chunga128a7b2012-04-30 15:23:15 -0700796 }
797 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700798 }
799
Adam Cohen60b07122011-11-14 17:26:06 -0800800 public void setPageSpacing(int pageSpacing) {
801 mPageSpacing = pageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -0700802 requestLayout();
Adam Cohen60b07122011-11-14 17:26:06 -0800803 }
804
Winson Chung321e9ee2010-08-09 13:37:56 -0700805 @Override
Michael Jurka28750fb2010-09-24 17:43:49 -0700806 protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
Adam Cohendcd297f2013-06-18 13:13:40 -0700807 if (!mIsDataReady || getChildCount() == 0) {
Winson Chungf0ea4d32011-06-06 14:27:16 -0700808 return;
809 }
810
Winson Chung785d2eb2011-04-14 16:08:02 -0700811 if (DEBUG) Log.d(TAG, "PagedView.onLayout()");
Winson Chung321e9ee2010-08-09 13:37:56 -0700812 final int childCount = getChildCount();
Winson Chung321e9ee2010-08-09 13:37:56 -0700813
Adam Cohenedb40762013-07-18 16:45:45 -0700814 int screenWidth = getViewportWidth();
815
Adam Cohen7d30a372013-07-01 17:03:59 -0700816 int offsetX = getViewportOffsetX();
817 int offsetY = getViewportOffsetY();
818
819 // Update the viewport offsets
820 mViewport.offset(offsetX, offsetY);
821
Adam Cohen0ffac432013-07-10 11:19:26 -0700822 final boolean isRtl = isLayoutRtl();
823
824 final int startIndex = isRtl ? childCount - 1 : 0;
825 final int endIndex = isRtl ? -1 : childCount;
826 final int delta = isRtl ? -1 : 1;
827
Adam Cohen7d30a372013-07-01 17:03:59 -0700828 int verticalPadding = getPaddingTop() + getPaddingBottom();
Adam Cohenedb40762013-07-18 16:45:45 -0700829 int childLeft = offsetX + (screenWidth - getChildWidth(startIndex)) / 2;
830
831 if (mPageScrolls == null || getChildCount() != mChildCountOnLastLayout) {
832 mPageScrolls = new int[getChildCount()];
833 }
834
Adam Cohen0ffac432013-07-10 11:19:26 -0700835 for (int i = startIndex; i != endIndex; i += delta) {
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700836
Adam Cohen22f823d2011-09-01 17:22:18 -0700837 final View child = getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -0700838 LayoutParams lp = (LayoutParams) child.getLayoutParams();
839 int childTop;
840
841 if (lp.isFullScreenPage) {
842 childTop = offsetY;
843 } else {
844 childTop = offsetY + getPaddingTop();
845 if (mCenterPagesVertically) {
846 childTop += ((getViewportHeight() - verticalPadding) - child.getMeasuredHeight()) / 2;
847 }
Adam Cohen7d30a372013-07-01 17:03:59 -0700848 }
Adam Cohen96d30a12013-07-16 18:13:21 -0700849
Winson Chung321e9ee2010-08-09 13:37:56 -0700850 if (child.getVisibility() != View.GONE) {
Adam Cohen96d30a12013-07-16 18:13:21 -0700851 final int childWidth = child.getMeasuredWidth();
Adam Lesinski6b879f02010-11-04 16:15:23 -0700852 final int childHeight = child.getMeasuredHeight();
Michael Jurkad3ef3062010-11-23 16:23:58 -0800853
Winson Chung785d2eb2011-04-14 16:08:02 -0700854 if (DEBUG) Log.d(TAG, "\tlayout-child" + i + ": " + childLeft + ", " + childTop);
Adam Lesinski6b879f02010-11-04 16:15:23 -0700855 child.layout(childLeft, childTop,
Michael Jurkad3ef3062010-11-23 16:23:58 -0800856 childLeft + child.getMeasuredWidth(), childTop + childHeight);
Adam Cohenedb40762013-07-18 16:45:45 -0700857
858 // We assume the left and right padding are equal, and hence center the pages
859 // horizontally
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700860 int scrollOffset = (getViewportWidth() - childWidth) / 2;
Adam Cohenedb40762013-07-18 16:45:45 -0700861 mPageScrolls[i] = childLeft - scrollOffset - offsetX;
862
Adam Cohen6ad0e7d2013-07-24 13:55:41 -0700863 if (i != endIndex - delta) {
864 int nextScrollOffset = (getViewportWidth() - getChildWidth(i + delta)) / 2;
865 childLeft += childWidth + nextScrollOffset;
866 }
Winson Chung321e9ee2010-08-09 13:37:56 -0700867 }
868 }
Winson Chungc3665fa2011-09-14 17:56:27 -0700869
870 if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
871 setHorizontalScrollBarEnabled(false);
Michael Jurkadd6c0912012-01-16 06:46:20 -0800872 updateCurrentPageScroll();
Winson Chungc3665fa2011-09-14 17:56:27 -0700873 setHorizontalScrollBarEnabled(true);
874 mFirstLayout = false;
875 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700876
877 if (childCount > 0) {
878 final int index = isLayoutRtl() ? 0 : childCount - 1;
Adam Cohenedb40762013-07-18 16:45:45 -0700879 mMaxScrollX = getScrollForPage(index);
Adam Cohenf698c6e2013-07-17 18:44:25 -0700880 } else {
881 mMaxScrollX = 0;
882 }
883
884 if (mScroller.isFinished() && mChildCountOnLastLayout != getChildCount() &&
885 !mDeferringForDelete) {
Winson Chung8c87cd82013-07-23 16:20:10 -0700886 if (mRestorePage > -1) {
887 setCurrentPage(mRestorePage);
888 mRestorePage = -1;
889 } else {
890 setCurrentPage(getNextPage());
891 }
Adam Cohenf698c6e2013-07-17 18:44:25 -0700892 }
893 mChildCountOnLastLayout = getChildCount();
Winson Chunge3193b92010-09-10 11:44:42 -0700894 }
895
Adam Cohenf34bab52010-09-30 14:11:56 -0700896 protected void screenScrolled(int screenCenter) {
Michael Jurka869390b2012-05-06 15:55:19 -0700897 boolean isInOverscroll = mOverScrollX < 0 || mOverScrollX > mMaxScrollX;
898
899 if (mFadeInAdjacentScreens && !isInOverscroll) {
Adam Cohen73894962011-10-31 13:17:17 -0700900 for (int i = 0; i < getChildCount(); i++) {
901 View child = getChildAt(i);
902 if (child != null) {
903 float scrollProgress = getScrollProgress(screenCenter, child, i);
904 float alpha = 1 - Math.abs(scrollProgress);
Michael Jurka7372c592012-01-16 04:21:35 -0800905 child.setAlpha(alpha);
Adam Cohen73894962011-10-31 13:17:17 -0700906 }
907 }
908 invalidate();
909 }
Adam Cohenf34bab52010-09-30 14:11:56 -0700910 }
911
Winson Chunge3193b92010-09-10 11:44:42 -0700912 @Override
Michael Jurka8b805b12012-04-18 14:23:14 -0700913 public void onChildViewAdded(View parent, View child) {
Winson Chungd2be3812013-07-16 11:11:32 -0700914 // Update the page indicator, we don't update the page indicator as we
915 // add/remove pages
916 if (mPageIndicator != null && !isReordering(false)) {
917 mPageIndicator.addMarker(indexOfChild(child));
918 }
919
Adam Cohen2591f6a2011-10-25 14:36:40 -0700920 // This ensures that when children are added, they get the correct transforms / alphas
921 // in accordance with any scroll effects.
922 mForceScreenScrolled = true;
Adam Cohen7d30a372013-07-01 17:03:59 -0700923 mRecomputePageSpacing = true;
Adam Cohen96d30a12013-07-16 18:13:21 -0700924
Adam Cohen2591f6a2011-10-25 14:36:40 -0700925 invalidate();
926 }
927
Michael Jurka8b805b12012-04-18 14:23:14 -0700928 @Override
929 public void onChildViewRemoved(View parent, View child) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700930 mForceScreenScrolled = true;
931 invalidate();
Michael Jurka8b805b12012-04-18 14:23:14 -0700932 }
933
Winson Chungd2be3812013-07-16 11:11:32 -0700934 private void removeMarkerForView(int index) {
935 // Update the page indicator, we don't update the page indicator as we
936 // add/remove pages
937 if (mPageIndicator != null && !isReordering(false)) {
938 mPageIndicator.removeMarker(index);
939 }
940 }
941
942 @Override
943 public void removeView(View v) {
944 // XXX: We should find a better way to hook into this before the view
945 // gets removed form its parent...
946 removeMarkerForView(indexOfChild(v));
947 super.removeView(v);
948 }
949 @Override
950 public void removeViewInLayout(View v) {
951 // XXX: We should find a better way to hook into this before the view
952 // gets removed form its parent...
953 removeMarkerForView(indexOfChild(v));
954 super.removeViewInLayout(v);
955 }
956 @Override
957 public void removeViewAt(int index) {
958 // XXX: We should find a better way to hook into this before the view
959 // gets removed form its parent...
960 removeViewAt(index);
961 super.removeViewAt(index);
962 }
963 @Override
964 public void removeAllViewsInLayout() {
965 // Update the page indicator, we don't update the page indicator as we
966 // add/remove pages
967 if (mPageIndicator != null) {
968 mPageIndicator.removeAllMarkers();
969 }
970
971 super.removeAllViewsInLayout();
972 }
973
Adam Cohen73894962011-10-31 13:17:17 -0700974 protected int getChildOffset(int index) {
Adam Cohen7d30a372013-07-01 17:03:59 -0700975 if (index < 0 || index > getChildCount() - 1) return 0;
976
Adam Cohen0ffac432013-07-10 11:19:26 -0700977 final boolean isRtl = isLayoutRtl();
Adam Cohen73894962011-10-31 13:17:17 -0700978
Adam Cohenf698c6e2013-07-17 18:44:25 -0700979 if (isRtl) index = getChildCount() - index - 1;
980 int offset = getPageAt(index).getLeft() - getViewportOffsetX();
Adam Cohen73894962011-10-31 13:17:17 -0700981
Adam Cohenf698c6e2013-07-17 18:44:25 -0700982 return offset;
Adam Cohen73894962011-10-31 13:17:17 -0700983 }
984
Winson Chungc9ca2982013-07-19 12:07:38 -0700985 void getReorderablePages(int[] range) {
986 range[0] = 0;
987 range[1] = getChildCount() - 1;
Adam Cohen7d30a372013-07-01 17:03:59 -0700988 }
989
Michael Jurkadde558b2011-11-09 22:09:06 -0800990 protected void getVisiblePages(int[] range) {
Michael Jurka0142d492010-08-25 17:46:15 -0700991 final int pageCount = getChildCount();
Winson Chungc9ca2982013-07-19 12:07:38 -0700992 mTmpIntPoint[0] = mTmpIntPoint[1] = 0;
Michael Jurka4ff7d792012-04-02 03:46:50 -0700993
Michael Jurkac4fb9172010-09-02 17:19:20 -0700994 if (pageCount > 0) {
Winson Chungc9ca2982013-07-19 12:07:38 -0700995 int viewportWidth = getViewportWidth();
Adam Cohen7d30a372013-07-01 17:03:59 -0700996 int leftScreen = 0;
Michael Jurkac4fb9172010-09-02 17:19:20 -0700997 int rightScreen = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -0700998
Winson Chungc9ca2982013-07-19 12:07:38 -0700999 for (leftScreen = getNextPage(); leftScreen >= 0; --leftScreen) {
1000 View currPage = getPageAt(leftScreen);
1001
1002 // Check if the right edge of the page is in the viewport
1003 mTmpIntPoint[0] = currPage.getMeasuredWidth();
1004 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1005 if (mTmpIntPoint[0] < 0) {
1006 break;
1007 }
1008 }
1009 for (rightScreen = getNextPage(); rightScreen < getChildCount(); ++rightScreen) {
1010 View currPage = getPageAt(rightScreen);
1011
1012 // Check if the left edge of the page is in the viewport
1013 mTmpIntPoint[0] = 0;
1014 DragLayer.getDescendantCoordRelativeToParent(currPage, this, mTmpIntPoint, false);
1015 if (mTmpIntPoint[0] >= viewportWidth) {
1016 break;
1017 }
1018 }
1019 range[0] = Math.max(0, leftScreen);
1020 range[1] = Math.min(rightScreen, getChildCount() - 1);
Michael Jurkadde558b2011-11-09 22:09:06 -08001021 } else {
1022 range[0] = -1;
1023 range[1] = -1;
1024 }
1025 }
1026
Michael Jurka920d7f42012-05-14 16:29:55 -07001027 protected boolean shouldDrawChild(View child) {
1028 return child.getAlpha() > 0;
1029 }
1030
Michael Jurkadde558b2011-11-09 22:09:06 -08001031 @Override
1032 protected void dispatchDraw(Canvas canvas) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001033 int halfScreenSize = getViewportWidth() / 2;
Michael Jurka8b805b12012-04-18 14:23:14 -07001034 // mOverScrollX is equal to getScrollX() when we're within the normal scroll range.
1035 // Otherwise it is equal to the scaled overscroll position.
Adam Cohenebea84d2011-11-09 17:20:41 -08001036 int screenCenter = mOverScrollX + halfScreenSize;
Michael Jurkadde558b2011-11-09 22:09:06 -08001037
1038 if (screenCenter != mLastScreenCenter || mForceScreenScrolled) {
Michael Jurkab06d95f2012-04-02 06:26:53 -07001039 // set mForceScreenScrolled before calling screenScrolled so that screenScrolled can
1040 // set it for the next frame
1041 mForceScreenScrolled = false;
Michael Jurkadde558b2011-11-09 22:09:06 -08001042 screenScrolled(screenCenter);
1043 mLastScreenCenter = screenCenter;
Michael Jurkadde558b2011-11-09 22:09:06 -08001044 }
1045
1046 // Find out which screens are visible; as an optimization we only call draw on them
1047 final int pageCount = getChildCount();
1048 if (pageCount > 0) {
1049 getVisiblePages(mTempVisiblePagesRange);
1050 final int leftScreen = mTempVisiblePagesRange[0];
1051 final int rightScreen = mTempVisiblePagesRange[1];
Winson Chungc6f10b92011-11-14 11:39:07 -08001052 if (leftScreen != -1 && rightScreen != -1) {
1053 final long drawingTime = getDrawingTime();
1054 // Clip to the bounds
1055 canvas.save();
Michael Jurka8b805b12012-04-18 14:23:14 -07001056 canvas.clipRect(getScrollX(), getScrollY(), getScrollX() + getRight() - getLeft(),
1057 getScrollY() + getBottom() - getTop());
Michael Jurka0142d492010-08-25 17:46:15 -07001058
Adam Cohen7d30a372013-07-01 17:03:59 -07001059 // Draw all the children, leaving the drag view for last
1060 for (int i = pageCount - 1; i >= 0; i--) {
Michael Jurka80c69852011-12-16 14:16:32 -08001061 final View v = getPageAt(i);
Adam Cohen7d30a372013-07-01 17:03:59 -07001062 if (v == mDragView) continue;
Michael Jurka5e368ff2012-05-14 23:13:15 -07001063 if (mForceDrawAllChildrenNextFrame ||
1064 (leftScreen <= i && i <= rightScreen && shouldDrawChild(v))) {
Michael Jurka80c69852011-12-16 14:16:32 -08001065 drawChild(canvas, v, drawingTime);
Michael Jurka80c69852011-12-16 14:16:32 -08001066 }
Winson Chungc6f10b92011-11-14 11:39:07 -08001067 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001068 // Draw the drag view on top (if there is one)
1069 if (mDragView != null) {
1070 drawChild(canvas, mDragView, drawingTime);
1071 }
1072
Michael Jurka5e368ff2012-05-14 23:13:15 -07001073 mForceDrawAllChildrenNextFrame = false;
Winson Chungc6f10b92011-11-14 11:39:07 -08001074 canvas.restore();
Michael Jurkac4fb9172010-09-02 17:19:20 -07001075 }
Michael Jurka0142d492010-08-25 17:46:15 -07001076 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001077 }
1078
1079 @Override
1080 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
Adam Cohenae4f1552011-10-20 00:15:42 -07001081 int page = indexToPage(indexOfChild(child));
Winson Chung86f77532010-08-24 11:08:22 -07001082 if (page != mCurrentPage || !mScroller.isFinished()) {
1083 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001084 return true;
1085 }
1086 return false;
1087 }
1088
1089 @Override
1090 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
Winson Chung86f77532010-08-24 11:08:22 -07001091 int focusablePage;
1092 if (mNextPage != INVALID_PAGE) {
1093 focusablePage = mNextPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001094 } else {
Winson Chung86f77532010-08-24 11:08:22 -07001095 focusablePage = mCurrentPage;
Winson Chung321e9ee2010-08-09 13:37:56 -07001096 }
Winson Chung86f77532010-08-24 11:08:22 -07001097 View v = getPageAt(focusablePage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001098 if (v != null) {
Adam Cohen76fc0852011-06-17 13:26:23 -07001099 return v.requestFocus(direction, previouslyFocusedRect);
Winson Chung321e9ee2010-08-09 13:37:56 -07001100 }
1101 return false;
1102 }
1103
1104 @Override
1105 public boolean dispatchUnhandledMove(View focused, int direction) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001106 // XXX-RTL: This will be fixed in a future CL
Winson Chung321e9ee2010-08-09 13:37:56 -07001107 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001108 if (getCurrentPage() > 0) {
1109 snapToPage(getCurrentPage() - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001110 return true;
1111 }
1112 } else if (direction == View.FOCUS_RIGHT) {
Winson Chung86f77532010-08-24 11:08:22 -07001113 if (getCurrentPage() < getPageCount() - 1) {
1114 snapToPage(getCurrentPage() + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07001115 return true;
1116 }
1117 }
1118 return super.dispatchUnhandledMove(focused, direction);
1119 }
1120
1121 @Override
1122 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001123 // XXX-RTL: This will be fixed in a future CL
Winson Chung86f77532010-08-24 11:08:22 -07001124 if (mCurrentPage >= 0 && mCurrentPage < getPageCount()) {
alanvaf519952012-05-07 17:33:22 -07001125 getPageAt(mCurrentPage).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001126 }
1127 if (direction == View.FOCUS_LEFT) {
Winson Chung86f77532010-08-24 11:08:22 -07001128 if (mCurrentPage > 0) {
alanvaf519952012-05-07 17:33:22 -07001129 getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001130 }
1131 } else if (direction == View.FOCUS_RIGHT){
Winson Chung86f77532010-08-24 11:08:22 -07001132 if (mCurrentPage < getPageCount() - 1) {
alanvaf519952012-05-07 17:33:22 -07001133 getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode);
Winson Chung321e9ee2010-08-09 13:37:56 -07001134 }
1135 }
1136 }
1137
1138 /**
1139 * If one of our descendant views decides that it could be focused now, only
Winson Chung86f77532010-08-24 11:08:22 -07001140 * pass that along if it's on the current page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001141 *
Winson Chung86f77532010-08-24 11:08:22 -07001142 * This happens when live folders requery, and if they're off page, they
1143 * end up calling requestFocus, which pulls it on page.
Winson Chung321e9ee2010-08-09 13:37:56 -07001144 */
1145 @Override
1146 public void focusableViewAvailable(View focused) {
Winson Chung86f77532010-08-24 11:08:22 -07001147 View current = getPageAt(mCurrentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001148 View v = focused;
1149 while (true) {
1150 if (v == current) {
1151 super.focusableViewAvailable(focused);
1152 return;
1153 }
1154 if (v == this) {
1155 return;
1156 }
1157 ViewParent parent = v.getParent();
1158 if (parent instanceof View) {
1159 v = (View)v.getParent();
1160 } else {
1161 return;
1162 }
1163 }
1164 }
1165
1166 /**
1167 * {@inheritDoc}
1168 */
1169 @Override
1170 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1171 if (disallowIntercept) {
1172 // We need to make sure to cancel our long press if
1173 // a scrollable widget takes over touch events
Adam Cohen22f823d2011-09-01 17:22:18 -07001174 final View currentPage = getPageAt(mCurrentPage);
Winson Chung86f77532010-08-24 11:08:22 -07001175 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001176 }
1177 super.requestDisallowInterceptTouchEvent(disallowIntercept);
1178 }
1179
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001180 /**
1181 * Return true if a tap at (x, y) should trigger a flip to the previous page.
1182 */
1183 protected boolean hitsPreviousPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001184 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001185 if (isLayoutRtl()) {
1186 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001187 offset + mPageSpacing));
Adam Cohen0ffac432013-07-10 11:19:26 -07001188 }
Adam Cohenedb40762013-07-18 16:45:45 -07001189 return (x < getViewportOffsetX() + offset - mPageSpacing);
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001190 }
1191
1192 /**
1193 * Return true if a tap at (x, y) should trigger a flip to the next page.
1194 */
1195 protected boolean hitsNextPage(float x, float y) {
Adam Cohenedb40762013-07-18 16:45:45 -07001196 int offset = (getViewportWidth() - getChildWidth(mCurrentPage)) / 2;
Adam Cohen0ffac432013-07-10 11:19:26 -07001197 if (isLayoutRtl()) {
Adam Cohenedb40762013-07-18 16:45:45 -07001198 return (x < getViewportOffsetX() + offset - mPageSpacing);
Adam Cohen0ffac432013-07-10 11:19:26 -07001199 }
1200 return (x > (getViewportOffsetX() + getViewportWidth() -
Adam Cohenedb40762013-07-18 16:45:45 -07001201 offset + mPageSpacing));
Adam Cohen7d30a372013-07-01 17:03:59 -07001202 }
Winson Chung52aee602013-01-30 12:01:02 -08001203
Adam Cohen7d30a372013-07-01 17:03:59 -07001204 /** Returns whether x and y originated within the buffered viewport */
1205 private boolean isTouchPointInViewportWithBuffer(int x, int y) {
1206 mTmpRect.set(mViewport.left - mViewport.width() / 2, mViewport.top,
1207 mViewport.right + mViewport.width() / 2, mViewport.bottom);
1208 return mTmpRect.contains(x, y);
1209 }
1210
1211 /** Returns whether x and y originated within the current page view bounds */
1212 private boolean isTouchPointInCurrentPage(int x, int y) {
1213 View v = getPageAt(getCurrentPage());
1214 if (v != null) {
1215 mTmpRect.set((v.getLeft() - getScrollX()), 0, (v.getRight() - getScrollX()),
1216 v.getBottom());
1217 return mTmpRect.contains(x, y);
1218 }
1219 return false;
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001220 }
1221
Winson Chung321e9ee2010-08-09 13:37:56 -07001222 @Override
1223 public boolean onInterceptTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001224 if (DISABLE_TOUCH_INTERACTION) {
1225 return false;
1226 }
1227
Winson Chung321e9ee2010-08-09 13:37:56 -07001228 /*
1229 * This method JUST determines whether we want to intercept the motion.
1230 * If we return true, onTouchEvent will be called and we do the actual
1231 * scrolling there.
1232 */
Adam Cohen6342bba2011-03-10 11:33:35 -08001233 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001234
Winson Chung45e1d6e2010-11-09 17:19:49 -08001235 // Skip touch handling if there are no pages to swipe
1236 if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
1237
Winson Chung321e9ee2010-08-09 13:37:56 -07001238 /*
1239 * Shortcut the most recurring case: the user is in the dragging
1240 * state and he is moving his finger. We want to intercept this
1241 * motion.
1242 */
1243 final int action = ev.getAction();
1244 if ((action == MotionEvent.ACTION_MOVE) &&
1245 (mTouchState == TOUCH_STATE_SCROLLING)) {
1246 return true;
1247 }
1248
Winson Chung321e9ee2010-08-09 13:37:56 -07001249 switch (action & MotionEvent.ACTION_MASK) {
1250 case MotionEvent.ACTION_MOVE: {
1251 /*
1252 * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check
1253 * whether the user has moved far enough from his original down touch.
1254 */
Michael Jurka1ff706b2010-09-14 17:35:20 -07001255 if (mActivePointerId != INVALID_POINTER) {
1256 determineScrollingStart(ev);
1257 break;
1258 }
1259 // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN
1260 // event. in that case, treat the first occurence of a move event as a ACTION_DOWN
1261 // i.e. fall through to the next case (don't break)
1262 // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events
1263 // while it's small- this was causing a crash before we checked for INVALID_POINTER)
Winson Chung321e9ee2010-08-09 13:37:56 -07001264 }
1265
1266 case MotionEvent.ACTION_DOWN: {
1267 final float x = ev.getX();
1268 final float y = ev.getY();
1269 // Remember location of down touch
1270 mDownMotionX = x;
Adam Cohen7d30a372013-07-01 17:03:59 -07001271 mDownMotionY = y;
1272 mDownScrollX = getScrollX();
Winson Chung321e9ee2010-08-09 13:37:56 -07001273 mLastMotionX = x;
1274 mLastMotionY = y;
Adam Cohen7d30a372013-07-01 17:03:59 -07001275 float[] p = mapPointFromViewToParent(this, x, y);
1276 mParentDownMotionX = p[0];
1277 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001278 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001279 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001280 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001281
1282 // Determine if the down event is within the threshold to be an edge swipe
1283 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1284 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1285 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1286 mDownEventOnEdge = true;
1287 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001288
1289 /*
1290 * If being flinged and user touches the screen, initiate drag;
1291 * otherwise don't. mScroller.isFinished should be false when
1292 * being flinged.
1293 */
Michael Jurkafd177c12010-10-19 15:50:43 -07001294 final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001295 final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
1296 if (finishedScrolling) {
1297 mTouchState = TOUCH_STATE_REST;
1298 mScroller.abortAnimation();
1299 } else {
Adam Cohen7d30a372013-07-01 17:03:59 -07001300 if (isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)) {
1301 mTouchState = TOUCH_STATE_SCROLLING;
1302 } else {
1303 mTouchState = TOUCH_STATE_REST;
1304 }
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001305 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001306
Winson Chung86f77532010-08-24 11:08:22 -07001307 // check if this can be the beginning of a tap on the side of the pages
Winson Chung321e9ee2010-08-09 13:37:56 -07001308 // to scroll the current page
Adam Cohen7d30a372013-07-01 17:03:59 -07001309 if (!DISABLE_TOUCH_SIDE_PAGES) {
1310 if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
1311 if (getChildCount() > 0) {
1312 if (hitsPreviousPage(x, y)) {
1313 mTouchState = TOUCH_STATE_PREV_PAGE;
1314 } else if (hitsNextPage(x, y)) {
1315 mTouchState = TOUCH_STATE_NEXT_PAGE;
1316 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001317 }
1318 }
1319 }
1320 break;
1321 }
1322
Winson Chung321e9ee2010-08-09 13:37:56 -07001323 case MotionEvent.ACTION_UP:
Jeff Brown1d0867c2010-12-02 18:27:39 -08001324 case MotionEvent.ACTION_CANCEL:
Adam Cohen7d30a372013-07-01 17:03:59 -07001325 resetTouchState();
1326 // Just intercept the touch event on up if we tap outside the strict viewport
1327 if (!isTouchPointInCurrentPage((int) mLastMotionX, (int) mLastMotionY)) {
1328 return true;
1329 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001330 break;
1331
1332 case MotionEvent.ACTION_POINTER_UP:
1333 onSecondaryPointerUp(ev);
Adam Cohen6342bba2011-03-10 11:33:35 -08001334 releaseVelocityTracker();
Winson Chung321e9ee2010-08-09 13:37:56 -07001335 break;
1336 }
1337
1338 /*
1339 * The only time we want to intercept motion events is if we are in the
1340 * drag mode.
1341 */
1342 return mTouchState != TOUCH_STATE_REST;
1343 }
1344
Adam Cohenf8d28232011-02-01 21:47:00 -08001345 protected void determineScrollingStart(MotionEvent ev) {
1346 determineScrollingStart(ev, 1.0f);
1347 }
1348
Winson Chung321e9ee2010-08-09 13:37:56 -07001349 /*
1350 * Determines if we should change the touch state to start scrolling after the
1351 * user moves their touch point too far.
1352 */
Adam Cohenf8d28232011-02-01 21:47:00 -08001353 protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001354 // Disallow scrolling if we don't have a valid pointer index
Winson Chung321e9ee2010-08-09 13:37:56 -07001355 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001356 if (pointerIndex == -1) return;
1357
1358 // Disallow scrolling if we started the gesture from outside the viewport
Winson Chung321e9ee2010-08-09 13:37:56 -07001359 final float x = ev.getX(pointerIndex);
1360 final float y = ev.getY(pointerIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001361 if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
1362
1363 // If we're only allowing edge swipes, we break out early if the down event wasn't
1364 // at the edge.
1365 if (mOnlyAllowEdgeSwipes && !mDownEventOnEdge) return;
1366
Winson Chung321e9ee2010-08-09 13:37:56 -07001367 final int xDiff = (int) Math.abs(x - mLastMotionX);
1368 final int yDiff = (int) Math.abs(y - mLastMotionY);
1369
Adam Cohenf8d28232011-02-01 21:47:00 -08001370 final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
Winson Chung321e9ee2010-08-09 13:37:56 -07001371 boolean xPaged = xDiff > mPagingTouchSlop;
1372 boolean xMoved = xDiff > touchSlop;
1373 boolean yMoved = yDiff > touchSlop;
1374
Adam Cohenf8d28232011-02-01 21:47:00 -08001375 if (xMoved || xPaged || yMoved) {
Michael Jurka0142d492010-08-25 17:46:15 -07001376 if (mUsePagingTouchSlop ? xPaged : xMoved) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001377 // Scroll if the user moved far enough along the X axis
1378 mTouchState = TOUCH_STATE_SCROLLING;
Adam Cohen6342bba2011-03-10 11:33:35 -08001379 mTotalMotionX += Math.abs(mLastMotionX - x);
Winson Chung321e9ee2010-08-09 13:37:56 -07001380 mLastMotionX = x;
Winson Chungc0844aa2011-02-02 15:25:58 -08001381 mLastMotionXRemainder = 0;
Adam Cohen7d30a372013-07-01 17:03:59 -07001382 mTouchX = getViewportOffsetX() + getScrollX();
Michael Jurka0142d492010-08-25 17:46:15 -07001383 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1384 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07001385 }
Adam Cohenf8d28232011-02-01 21:47:00 -08001386 }
1387 }
1388
Adam Cohen7d30a372013-07-01 17:03:59 -07001389 protected float getMaxScrollProgress() {
1390 return 1.0f;
1391 }
1392
Adam Cohenf8d28232011-02-01 21:47:00 -08001393 protected void cancelCurrentPageLongPress() {
1394 if (mAllowLongPress) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001395 //mAllowLongPress = false;
Adam Cohenf8d28232011-02-01 21:47:00 -08001396 // Try canceling the long press. It could also have been scheduled
1397 // by a distant descendant, so use the mAllowLongPress flag to block
1398 // everything
1399 final View currentPage = getPageAt(mCurrentPage);
1400 if (currentPage != null) {
1401 currentPage.cancelLongPress();
Winson Chung321e9ee2010-08-09 13:37:56 -07001402 }
1403 }
1404 }
1405
Adam Cohen7d30a372013-07-01 17:03:59 -07001406 protected float getBoundedScrollProgress(int screenCenter, View v, int page) {
1407 final int halfScreenSize = getViewportWidth() / 2;
1408
1409 screenCenter = Math.min(getScrollX() + halfScreenSize, screenCenter);
1410 screenCenter = Math.max(halfScreenSize, screenCenter);
1411
1412 return getScrollProgress(screenCenter, v, page);
1413 }
1414
Adam Cohenb5ba0972011-09-07 18:02:31 -07001415 protected float getScrollProgress(int screenCenter, View v, int page) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001416 final int halfScreenSize = getViewportWidth() / 2;
Adam Cohenb5ba0972011-09-07 18:02:31 -07001417
Adam Cohen96d30a12013-07-16 18:13:21 -07001418 int totalDistance = v.getMeasuredWidth() + mPageSpacing;
Adam Cohenedb40762013-07-18 16:45:45 -07001419 int delta = screenCenter - (getScrollForPage(page) + halfScreenSize);
Adam Cohenb5ba0972011-09-07 18:02:31 -07001420
1421 float scrollProgress = delta / (totalDistance * 1.0f);
Adam Cohen7d30a372013-07-01 17:03:59 -07001422 scrollProgress = Math.min(scrollProgress, getMaxScrollProgress());
1423 scrollProgress = Math.max(scrollProgress, - getMaxScrollProgress());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001424 return scrollProgress;
1425 }
1426
Adam Cohenedb40762013-07-18 16:45:45 -07001427 public int getScrollForPage(int index) {
1428 if (mPageScrolls == null || index >= mPageScrolls.length) {
1429 return 0;
1430 } else {
1431 return mPageScrolls[index];
1432 }
1433 }
1434
Adam Cohene0f66b52010-11-23 15:06:07 -08001435 // This curve determines how the effect of scrolling over the limits of the page dimishes
1436 // as the user pulls further and further from the bounds
1437 private float overScrollInfluenceCurve(float f) {
1438 f -= 1.0f;
1439 return f * f * f + 1.0f;
1440 }
1441
Adam Cohenb5ba0972011-09-07 18:02:31 -07001442 protected void acceleratedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001443 int screenSize = getViewportWidth();
Adam Cohenb5ba0972011-09-07 18:02:31 -07001444
1445 // We want to reach the max over scroll effect when the user has
1446 // over scrolled half the size of the screen
1447 float f = OVERSCROLL_ACCELERATE_FACTOR * (amount / screenSize);
1448
1449 if (f == 0) return;
1450
1451 // Clamp this factor, f, to -1 < f < 1
1452 if (Math.abs(f) >= 1) {
1453 f /= Math.abs(f);
1454 }
1455
1456 int overScrollAmount = (int) Math.round(f * screenSize);
1457 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001458 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001459 super.scrollTo(0, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001460 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001461 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001462 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohenb5ba0972011-09-07 18:02:31 -07001463 }
1464 invalidate();
1465 }
1466
1467 protected void dampedOverScroll(float amount) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001468 int screenSize = getViewportWidth();
Adam Cohene0f66b52010-11-23 15:06:07 -08001469
1470 float f = (amount / screenSize);
1471
1472 if (f == 0) return;
1473 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1474
Adam Cohen7bfc9792011-01-28 13:52:37 -08001475 // Clamp this factor, f, to -1 < f < 1
1476 if (Math.abs(f) >= 1) {
1477 f /= Math.abs(f);
1478 }
1479
Adam Cohene0f66b52010-11-23 15:06:07 -08001480 int overScrollAmount = (int) Math.round(OVERSCROLL_DAMP_FACTOR * f * screenSize);
Adam Cohen68d73932010-11-15 10:50:58 -08001481 if (amount < 0) {
Adam Cohenebea84d2011-11-09 17:20:41 -08001482 mOverScrollX = overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001483 super.scrollTo(0, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001484 } else {
Adam Cohenebea84d2011-11-09 17:20:41 -08001485 mOverScrollX = mMaxScrollX + overScrollAmount;
Michael Jurka8b805b12012-04-18 14:23:14 -07001486 super.scrollTo(mMaxScrollX, getScrollY());
Adam Cohen68d73932010-11-15 10:50:58 -08001487 }
1488 invalidate();
1489 }
1490
Adam Cohenb5ba0972011-09-07 18:02:31 -07001491 protected void overScroll(float amount) {
1492 dampedOverScroll(amount);
1493 }
1494
Michael Jurkac5b262c2011-01-12 20:24:50 -08001495 protected float maxOverScroll() {
1496 // Using the formula in overScroll, assuming that f = 1.0 (which it should generally not
Adam Cohenb5ba0972011-09-07 18:02:31 -07001497 // exceed). Used to find out how much extra wallpaper we need for the over scroll effect
Michael Jurkac5b262c2011-01-12 20:24:50 -08001498 float f = 1.0f;
1499 f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f)));
1500 return OVERSCROLL_DAMP_FACTOR * f;
1501 }
1502
Winson Chung321e9ee2010-08-09 13:37:56 -07001503 @Override
1504 public boolean onTouchEvent(MotionEvent ev) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001505 if (DISABLE_TOUCH_INTERACTION) {
1506 return false;
1507 }
1508
Winson Chung45e1d6e2010-11-09 17:19:49 -08001509 // Skip touch handling if there are no pages to swipe
1510 if (getChildCount() <= 0) return super.onTouchEvent(ev);
1511
Michael Jurkab8f06722010-10-10 15:58:46 -07001512 acquireVelocityTrackerAndAddMovement(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001513
1514 final int action = ev.getAction();
1515
1516 switch (action & MotionEvent.ACTION_MASK) {
1517 case MotionEvent.ACTION_DOWN:
1518 /*
1519 * If being flinged and user touches, stop the fling. isFinished
1520 * will be false if being flinged.
1521 */
1522 if (!mScroller.isFinished()) {
1523 mScroller.abortAnimation();
1524 }
1525
1526 // Remember where the motion event started
1527 mDownMotionX = mLastMotionX = ev.getX();
Adam Cohen7d30a372013-07-01 17:03:59 -07001528 mDownMotionY = mLastMotionY = ev.getY();
1529 mDownScrollX = getScrollX();
1530 float[] p = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1531 mParentDownMotionX = p[0];
1532 mParentDownMotionY = p[1];
Winson Chungc0844aa2011-02-02 15:25:58 -08001533 mLastMotionXRemainder = 0;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001534 mTotalMotionX = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001535 mActivePointerId = ev.getPointerId(0);
Adam Cohen7d30a372013-07-01 17:03:59 -07001536
1537 // Determine if the down event is within the threshold to be an edge swipe
1538 int leftEdgeBoundary = getViewportOffsetX() + mEdgeSwipeRegionSize;
1539 int rightEdgeBoundary = getMeasuredWidth() - getViewportOffsetX() - mEdgeSwipeRegionSize;
1540 if ((mDownMotionX <= leftEdgeBoundary || mDownMotionX >= rightEdgeBoundary)) {
1541 mDownEventOnEdge = true;
1542 }
1543
Michael Jurka0142d492010-08-25 17:46:15 -07001544 if (mTouchState == TOUCH_STATE_SCROLLING) {
1545 pageBeginMoving();
1546 }
Winson Chung321e9ee2010-08-09 13:37:56 -07001547 break;
1548
1549 case MotionEvent.ACTION_MOVE:
1550 if (mTouchState == TOUCH_STATE_SCROLLING) {
1551 // Scroll to follow the motion event
1552 final int pointerIndex = ev.findPointerIndex(mActivePointerId);
Adam Cohen7d30a372013-07-01 17:03:59 -07001553
1554 if (pointerIndex == -1) return true;
1555
Winson Chung321e9ee2010-08-09 13:37:56 -07001556 final float x = ev.getX(pointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001557 final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
Winson Chung321e9ee2010-08-09 13:37:56 -07001558
Adam Cohenaefd4e12011-02-14 16:39:38 -08001559 mTotalMotionX += Math.abs(deltaX);
1560
Winson Chungc0844aa2011-02-02 15:25:58 -08001561 // Only scroll and update mLastMotionX if we have moved some discrete amount. We
1562 // keep the remainder because we are actually testing if we've moved from the last
1563 // scrolled position (which is discrete).
1564 if (Math.abs(deltaX) >= 1.0f) {
Adam Cohen68d73932010-11-15 10:50:58 -08001565 mTouchX += deltaX;
1566 mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
1567 if (!mDeferScrollUpdate) {
Winson Chungc0844aa2011-02-02 15:25:58 -08001568 scrollBy((int) deltaX, 0);
Winson Chung785d2eb2011-04-14 16:08:02 -07001569 if (DEBUG) Log.d(TAG, "onTouchEvent().Scrolling: " + deltaX);
Adam Cohen68d73932010-11-15 10:50:58 -08001570 } else {
1571 invalidate();
Winson Chung321e9ee2010-08-09 13:37:56 -07001572 }
Winson Chungc0844aa2011-02-02 15:25:58 -08001573 mLastMotionX = x;
1574 mLastMotionXRemainder = deltaX - (int) deltaX;
Winson Chung321e9ee2010-08-09 13:37:56 -07001575 } else {
1576 awakenScrollBars();
1577 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001578 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1579 // Update the last motion position
1580 mLastMotionX = ev.getX();
1581 mLastMotionY = ev.getY();
1582
1583 // Update the parent down so that our zoom animations take this new movement into
1584 // account
1585 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1586 mParentDownMotionX = pt[0];
1587 mParentDownMotionY = pt[1];
1588 updateDragViewTranslationDuringDrag();
1589
1590 // Find the closest page to the touch point
1591 final int dragViewIndex = indexOfChild(mDragView);
1592 int bufferSize = (int) (REORDERING_SIDE_PAGE_BUFFER_PERCENTAGE *
1593 getViewportWidth());
1594 int leftBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.left, 0)[0]
1595 + bufferSize);
1596 int rightBufferEdge = (int) (mapPointFromViewToParent(this, mViewport.right, 0)[0]
1597 - bufferSize);
1598
1599 // Change the drag view if we are hovering over the drop target
1600 boolean isHoveringOverDelete = isHoveringOverDeleteDropTarget(
1601 (int) mParentDownMotionX, (int) mParentDownMotionY);
1602 setPageHoveringOverDeleteDropTarget(dragViewIndex, isHoveringOverDelete);
1603
1604 if (DEBUG) Log.d(TAG, "leftBufferEdge: " + leftBufferEdge);
1605 if (DEBUG) Log.d(TAG, "rightBufferEdge: " + rightBufferEdge);
1606 if (DEBUG) Log.d(TAG, "mLastMotionX: " + mLastMotionX);
1607 if (DEBUG) Log.d(TAG, "mLastMotionY: " + mLastMotionY);
1608 if (DEBUG) Log.d(TAG, "mParentDownMotionX: " + mParentDownMotionX);
1609 if (DEBUG) Log.d(TAG, "mParentDownMotionY: " + mParentDownMotionY);
1610
1611 float parentX = mParentDownMotionX;
1612 int pageIndexToSnapTo = -1;
1613 if (parentX < leftBufferEdge && dragViewIndex > 0) {
1614 pageIndexToSnapTo = dragViewIndex - 1;
1615 } else if (parentX > rightBufferEdge && dragViewIndex < getChildCount() - 1) {
1616 pageIndexToSnapTo = dragViewIndex + 1;
1617 }
1618
1619 final int pageUnderPointIndex = pageIndexToSnapTo;
1620 if (pageUnderPointIndex > -1 && !isHoveringOverDelete) {
1621 mTempVisiblePagesRange[0] = 0;
1622 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07001623 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07001624 if (mTempVisiblePagesRange[0] <= pageUnderPointIndex &&
1625 pageUnderPointIndex <= mTempVisiblePagesRange[1] &&
1626 pageUnderPointIndex != mSidePageHoverIndex && mScroller.isFinished()) {
1627 mSidePageHoverIndex = pageUnderPointIndex;
1628 mSidePageHoverRunnable = new Runnable() {
1629 @Override
1630 public void run() {
1631 // Update the down scroll position to account for the fact that the
1632 // current page is moved
Adam Cohenedb40762013-07-18 16:45:45 -07001633 mDownScrollX = getScrollForPage(pageUnderPointIndex);
Adam Cohen7d30a372013-07-01 17:03:59 -07001634
1635 // Setup the scroll to the correct page before we swap the views
1636 snapToPage(pageUnderPointIndex);
1637
1638 // For each of the pages between the paged view and the drag view,
1639 // animate them from the previous position to the new position in
1640 // the layout (as a result of the drag view moving in the layout)
1641 int shiftDelta = (dragViewIndex < pageUnderPointIndex) ? -1 : 1;
1642 int lowerIndex = (dragViewIndex < pageUnderPointIndex) ?
1643 dragViewIndex + 1 : pageUnderPointIndex;
1644 int upperIndex = (dragViewIndex > pageUnderPointIndex) ?
1645 dragViewIndex - 1 : pageUnderPointIndex;
1646 for (int i = lowerIndex; i <= upperIndex; ++i) {
1647 View v = getChildAt(i);
1648 // dragViewIndex < pageUnderPointIndex, so after we remove the
1649 // drag view all subsequent views to pageUnderPointIndex will
1650 // shift down.
1651 int oldX = getViewportOffsetX() + getChildOffset(i);
1652 int newX = getViewportOffsetX() + getChildOffset(i + shiftDelta);
1653
1654 // Animate the view translation from its old position to its new
1655 // position
1656 AnimatorSet anim = (AnimatorSet) v.getTag(ANIM_TAG_KEY);
1657 if (anim != null) {
1658 anim.cancel();
1659 }
1660
1661 v.setTranslationX(oldX - newX);
1662 anim = new AnimatorSet();
1663 anim.setDuration(REORDERING_REORDER_REPOSITION_DURATION);
1664 anim.playTogether(
1665 ObjectAnimator.ofFloat(v, "translationX", 0f));
1666 anim.start();
1667 v.setTag(anim);
1668 }
1669
1670 removeView(mDragView);
1671 onRemoveView(mDragView, false);
1672 addView(mDragView, pageUnderPointIndex);
1673 onAddView(mDragView, pageUnderPointIndex);
1674 mSidePageHoverIndex = -1;
Winson Chungd2be3812013-07-16 11:11:32 -07001675 mPageIndicator.setActiveMarker(getNextPage());
Adam Cohen7d30a372013-07-01 17:03:59 -07001676 }
1677 };
1678 postDelayed(mSidePageHoverRunnable, REORDERING_SIDE_PAGE_HOVER_TIMEOUT);
1679 }
1680 } else {
1681 removeCallbacks(mSidePageHoverRunnable);
1682 mSidePageHoverIndex = -1;
1683 }
Adam Cohen564976a2010-10-13 18:52:07 -07001684 } else {
Winson Chung321e9ee2010-08-09 13:37:56 -07001685 determineScrollingStart(ev);
1686 }
1687 break;
1688
1689 case MotionEvent.ACTION_UP:
1690 if (mTouchState == TOUCH_STATE_SCROLLING) {
1691 final int activePointerId = mActivePointerId;
1692 final int pointerIndex = ev.findPointerIndex(activePointerId);
1693 final float x = ev.getX(pointerIndex);
1694 final VelocityTracker velocityTracker = mVelocityTracker;
1695 velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
1696 int velocityX = (int) velocityTracker.getXVelocity(activePointerId);
Winson Chung9cfd25f2010-10-24 16:09:28 -07001697 final int deltaX = (int) (x - mDownMotionX);
Adam Cohen96d30a12013-07-16 18:13:21 -07001698 final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth();
Adam Cohen00481b32011-11-18 12:03:48 -08001699 boolean isSignificantMove = Math.abs(deltaX) > pageWidth *
1700 SIGNIFICANT_MOVE_THRESHOLD;
Adam Cohenaefd4e12011-02-14 16:39:38 -08001701
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001702 mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x);
1703
Adam Cohen00481b32011-11-18 12:03:48 -08001704 boolean isFling = mTotalMotionX > MIN_LENGTH_FOR_FLING &&
Adam Cohen265b9a62011-12-07 14:37:18 -08001705 Math.abs(velocityX) > mFlingThresholdVelocity;
Adam Cohen00481b32011-11-18 12:03:48 -08001706
Adam Cohenaefd4e12011-02-14 16:39:38 -08001707 // In the case that the page is moved far to one direction and then is flung
1708 // in the opposite direction, we use a threshold to determine whether we should
1709 // just return to the starting page, or if we should skip one further.
1710 boolean returnToOriginalPage = false;
Adam Cohenb64cb5a2011-02-15 13:53:42 -08001711 if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD &&
Adam Cohen00481b32011-11-18 12:03:48 -08001712 Math.signum(velocityX) != Math.signum(deltaX) && isFling) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001713 returnToOriginalPage = true;
1714 }
1715
Adam Cohenaefd4e12011-02-14 16:39:38 -08001716 int finalPage;
1717 // We give flings precedence over large moves, which is why we short-circuit our
1718 // test for a large move if a fling has been registered. That is, a large
1719 // move to the left and fling to the right will register as a fling to the right.
Adam Cohen0ffac432013-07-10 11:19:26 -07001720 final boolean isRtl = isLayoutRtl();
1721 boolean isDeltaXLeft = isRtl ? deltaX > 0 : deltaX < 0;
1722 boolean isVelocityXLeft = isRtl ? velocityX > 0 : velocityX < 0;
1723 if (((isSignificantMove && !isDeltaXLeft && !isFling) ||
1724 (isFling && !isVelocityXLeft)) && mCurrentPage > 0) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001725 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1;
1726 snapToPageWithVelocity(finalPage, velocityX);
Adam Cohen0ffac432013-07-10 11:19:26 -07001727 } else if (((isSignificantMove && isDeltaXLeft && !isFling) ||
1728 (isFling && isVelocityXLeft)) &&
Winson Chung86f77532010-08-24 11:08:22 -07001729 mCurrentPage < getChildCount() - 1) {
Adam Cohenaefd4e12011-02-14 16:39:38 -08001730 finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1;
1731 snapToPageWithVelocity(finalPage, velocityX);
Winson Chung321e9ee2010-08-09 13:37:56 -07001732 } else {
1733 snapToDestination();
Adam Cohen0ffac432013-07-10 11:19:26 -07001734 } } else if (mTouchState == TOUCH_STATE_PREV_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001735 // at this point we have not moved beyond the touch slop
1736 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1737 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001738 int nextPage = Math.max(0, mCurrentPage - 1);
1739 if (nextPage != mCurrentPage) {
1740 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001741 } else {
1742 snapToDestination();
1743 }
Patrick Dubroyd0ce1ec2011-01-19 18:47:27 -08001744 } else if (mTouchState == TOUCH_STATE_NEXT_PAGE) {
Winson Chung321e9ee2010-08-09 13:37:56 -07001745 // at this point we have not moved beyond the touch slop
1746 // (otherwise mTouchState would be TOUCH_STATE_SCROLLING), so
1747 // we can just page
Winson Chung86f77532010-08-24 11:08:22 -07001748 int nextPage = Math.min(getChildCount() - 1, mCurrentPage + 1);
1749 if (nextPage != mCurrentPage) {
1750 snapToPage(nextPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07001751 } else {
1752 snapToDestination();
1753 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001754 } else if (mTouchState == TOUCH_STATE_REORDERING) {
1755 // Update the last motion position
1756 mLastMotionX = ev.getX();
1757 mLastMotionY = ev.getY();
1758
1759 // Update the parent down so that our zoom animations take this new movement into
1760 // account
1761 float[] pt = mapPointFromViewToParent(this, mLastMotionX, mLastMotionY);
1762 mParentDownMotionX = pt[0];
1763 mParentDownMotionY = pt[1];
1764 updateDragViewTranslationDuringDrag();
1765 boolean handledFling = false;
1766 if (!DISABLE_FLING_TO_DELETE) {
1767 // Check the velocity and see if we are flinging-to-delete
1768 PointF flingToDeleteVector = isFlingingToDelete();
1769 if (flingToDeleteVector != null) {
1770 onFlingToDelete(flingToDeleteVector);
1771 handledFling = true;
1772 }
1773 }
1774 if (!handledFling && isHoveringOverDeleteDropTarget((int) mParentDownMotionX,
1775 (int) mParentDownMotionY)) {
1776 onDropToDelete();
1777 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001778 } else {
Michael Jurkad771c962011-08-09 15:00:48 -07001779 onUnhandledTap(ev);
Winson Chung321e9ee2010-08-09 13:37:56 -07001780 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001781
1782 // Remove the callback to wait for the side page hover timeout
1783 removeCallbacks(mSidePageHoverRunnable);
1784 // End any intermediate reordering states
1785 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001786 break;
1787
1788 case MotionEvent.ACTION_CANCEL:
Michael Jurkab8f06722010-10-10 15:58:46 -07001789 if (mTouchState == TOUCH_STATE_SCROLLING) {
1790 snapToDestination();
1791 }
Adam Cohen7d30a372013-07-01 17:03:59 -07001792 resetTouchState();
Winson Chung321e9ee2010-08-09 13:37:56 -07001793 break;
1794
1795 case MotionEvent.ACTION_POINTER_UP:
1796 onSecondaryPointerUp(ev);
1797 break;
1798 }
1799
1800 return true;
1801 }
1802
Adam Cohen7d30a372013-07-01 17:03:59 -07001803 public void onFlingToDelete(View v) {}
1804 public void onRemoveView(View v, boolean deletePermanently) {}
1805 public void onRemoveViewAnimationCompleted() {}
1806 public void onAddView(View v, int index) {}
1807
1808 private void resetTouchState() {
1809 releaseVelocityTracker();
1810 endReordering();
1811 mTouchState = TOUCH_STATE_REST;
1812 mActivePointerId = INVALID_POINTER;
1813 mDownEventOnEdge = false;
1814 }
1815
1816 protected void onUnhandledTap(MotionEvent ev) {}
1817
Winson Chung185d7162011-02-28 13:47:29 -08001818 @Override
1819 public boolean onGenericMotionEvent(MotionEvent event) {
1820 if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
1821 switch (event.getAction()) {
1822 case MotionEvent.ACTION_SCROLL: {
1823 // Handle mouse (or ext. device) by shifting the page depending on the scroll
1824 final float vscroll;
1825 final float hscroll;
1826 if ((event.getMetaState() & KeyEvent.META_SHIFT_ON) != 0) {
1827 vscroll = 0;
1828 hscroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1829 } else {
1830 vscroll = -event.getAxisValue(MotionEvent.AXIS_VSCROLL);
1831 hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL);
1832 }
1833 if (hscroll != 0 || vscroll != 0) {
Adam Cohen0ffac432013-07-10 11:19:26 -07001834 boolean isForwardScroll = isLayoutRtl() ? (hscroll < 0 || vscroll < 0)
1835 : (hscroll > 0 || vscroll > 0);
1836 if (isForwardScroll) {
Winson Chung185d7162011-02-28 13:47:29 -08001837 scrollRight();
1838 } else {
1839 scrollLeft();
1840 }
1841 return true;
1842 }
1843 }
1844 }
1845 }
1846 return super.onGenericMotionEvent(event);
1847 }
1848
Michael Jurkab8f06722010-10-10 15:58:46 -07001849 private void acquireVelocityTrackerAndAddMovement(MotionEvent ev) {
1850 if (mVelocityTracker == null) {
1851 mVelocityTracker = VelocityTracker.obtain();
1852 }
1853 mVelocityTracker.addMovement(ev);
1854 }
1855
1856 private void releaseVelocityTracker() {
1857 if (mVelocityTracker != null) {
1858 mVelocityTracker.recycle();
1859 mVelocityTracker = null;
1860 }
1861 }
1862
Winson Chung321e9ee2010-08-09 13:37:56 -07001863 private void onSecondaryPointerUp(MotionEvent ev) {
1864 final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
1865 MotionEvent.ACTION_POINTER_INDEX_SHIFT;
1866 final int pointerId = ev.getPointerId(pointerIndex);
1867 if (pointerId == mActivePointerId) {
1868 // This was our active pointer going up. Choose a new
1869 // active pointer and adjust accordingly.
1870 // TODO: Make this decision more intelligent.
1871 final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
1872 mLastMotionX = mDownMotionX = ev.getX(newPointerIndex);
1873 mLastMotionY = ev.getY(newPointerIndex);
Winson Chungc0844aa2011-02-02 15:25:58 -08001874 mLastMotionXRemainder = 0;
Winson Chung321e9ee2010-08-09 13:37:56 -07001875 mActivePointerId = ev.getPointerId(newPointerIndex);
1876 if (mVelocityTracker != null) {
1877 mVelocityTracker.clear();
1878 }
1879 }
Jeff Brown1d0867c2010-12-02 18:27:39 -08001880 }
1881
Winson Chung321e9ee2010-08-09 13:37:56 -07001882 @Override
1883 public void requestChildFocus(View child, View focused) {
1884 super.requestChildFocus(child, focused);
Adam Cohenae4f1552011-10-20 00:15:42 -07001885 int page = indexToPage(indexOfChild(child));
Winson Chung97d85d22011-04-13 11:27:36 -07001886 if (page >= 0 && page != getCurrentPage() && !isInTouchMode()) {
Winson Chung86f77532010-08-24 11:08:22 -07001887 snapToPage(page);
Winson Chung321e9ee2010-08-09 13:37:56 -07001888 }
1889 }
1890
Winson Chung1908d072011-02-24 18:09:44 -08001891 protected int getChildWidth(int index) {
Adam Cohen96d30a12013-07-16 18:13:21 -07001892 return getPageAt(index).getMeasuredWidth();
Winson Chung1908d072011-02-24 18:09:44 -08001893 }
1894
Adam Cohen7d30a372013-07-01 17:03:59 -07001895 int getPageNearestToPoint(float x) {
1896 int index = 0;
1897 for (int i = 0; i < getChildCount(); ++i) {
1898 if (x < getChildAt(i).getRight() - getScrollX()) {
1899 return index;
1900 } else {
1901 index++;
1902 }
1903 }
1904 return Math.min(index, getChildCount() - 1);
1905 }
1906
Adam Cohend19d3ca2010-09-15 14:43:42 -07001907 int getPageNearestToCenterOfScreen() {
Adam Cohen22f823d2011-09-01 17:22:18 -07001908 int minDistanceFromScreenCenter = Integer.MAX_VALUE;
Winson Chung321e9ee2010-08-09 13:37:56 -07001909 int minDistanceFromScreenCenterIndex = -1;
Adam Cohen7d30a372013-07-01 17:03:59 -07001910 int screenCenter = getViewportOffsetX() + getScrollX() + (getViewportWidth() / 2);
Winson Chung321e9ee2010-08-09 13:37:56 -07001911 final int childCount = getChildCount();
1912 for (int i = 0; i < childCount; ++i) {
Adam Cohen22f823d2011-09-01 17:22:18 -07001913 View layout = (View) getPageAt(i);
Adam Cohen96d30a12013-07-16 18:13:21 -07001914 int childWidth = layout.getMeasuredWidth();
Winson Chung321e9ee2010-08-09 13:37:56 -07001915 int halfChildWidth = (childWidth / 2);
Adam Cohen7d30a372013-07-01 17:03:59 -07001916 int childCenter = getViewportOffsetX() + getChildOffset(i) + halfChildWidth;
Winson Chung321e9ee2010-08-09 13:37:56 -07001917 int distanceFromScreenCenter = Math.abs(childCenter - screenCenter);
1918 if (distanceFromScreenCenter < minDistanceFromScreenCenter) {
1919 minDistanceFromScreenCenter = distanceFromScreenCenter;
1920 minDistanceFromScreenCenterIndex = i;
1921 }
1922 }
Adam Cohend19d3ca2010-09-15 14:43:42 -07001923 return minDistanceFromScreenCenterIndex;
1924 }
1925
1926 protected void snapToDestination() {
1927 snapToPage(getPageNearestToCenterOfScreen(), PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001928 }
1929
Adam Cohene0f66b52010-11-23 15:06:07 -08001930 private static class ScrollInterpolator implements Interpolator {
1931 public ScrollInterpolator() {
1932 }
1933
1934 public float getInterpolation(float t) {
1935 t -= 1.0f;
1936 return t*t*t*t*t + 1;
1937 }
1938 }
1939
1940 // We want the duration of the page snap animation to be influenced by the distance that
1941 // the screen has to travel, however, we don't want this duration to be effected in a
1942 // purely linear fashion. Instead, we use this method to moderate the effect that the distance
1943 // of travel has on the overall snap duration.
1944 float distanceInfluenceForSnapDuration(float f) {
1945 f -= 0.5f; // center the values about 0.
1946 f *= 0.3f * Math.PI / 2.0f;
1947 return (float) Math.sin(f);
1948 }
1949
Michael Jurka0142d492010-08-25 17:46:15 -07001950 protected void snapToPageWithVelocity(int whichPage, int velocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001951 whichPage = Math.max(0, Math.min(whichPage, getChildCount() - 1));
Adam Cohen7d30a372013-07-01 17:03:59 -07001952 int halfScreenSize = getViewportWidth() / 2;
Adam Cohene0f66b52010-11-23 15:06:07 -08001953
Adam Cohenedb40762013-07-18 16:45:45 -07001954 final int newX = getScrollForPage(whichPage);
Adam Cohene0f66b52010-11-23 15:06:07 -08001955 int delta = newX - mUnboundedScrollX;
1956 int duration = 0;
1957
Adam Cohen265b9a62011-12-07 14:37:18 -08001958 if (Math.abs(velocity) < mMinFlingVelocity) {
Adam Cohene0f66b52010-11-23 15:06:07 -08001959 // If the velocity is low enough, then treat this more as an automatic page advance
1960 // as opposed to an apparent physical response to flinging
1961 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
1962 return;
1963 }
1964
1965 // Here we compute a "distance" that will be used in the computation of the overall
1966 // snap duration. This is a function of the actual distance that needs to be traveled;
1967 // we keep this value close to half screen size in order to reduce the variance in snap
1968 // duration as a function of the distance the page needs to travel.
Michael Jurka20b7ca92011-06-07 20:09:16 -07001969 float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize));
Adam Cohene0f66b52010-11-23 15:06:07 -08001970 float distance = halfScreenSize + halfScreenSize *
1971 distanceInfluenceForSnapDuration(distanceRatio);
1972
1973 velocity = Math.abs(velocity);
Adam Cohen265b9a62011-12-07 14:37:18 -08001974 velocity = Math.max(mMinSnapVelocity, velocity);
Adam Cohene0f66b52010-11-23 15:06:07 -08001975
1976 // we want the page's snap velocity to approximately match the velocity at which the
1977 // user flings, so we scale the duration by a value near to the derivative of the scroll
Michael Jurka20b7ca92011-06-07 20:09:16 -07001978 // interpolator at zero, ie. 5. We use 4 to make it a little slower.
1979 duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
Adam Cohene0f66b52010-11-23 15:06:07 -08001980
1981 snapToPage(whichPage, delta, duration);
Michael Jurka0142d492010-08-25 17:46:15 -07001982 }
1983
1984 protected void snapToPage(int whichPage) {
Winson Chung5f2aa4e2010-08-20 14:49:25 -07001985 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION);
Winson Chung321e9ee2010-08-09 13:37:56 -07001986 }
1987
Adam Cohen7d30a372013-07-01 17:03:59 -07001988 protected void snapToPageImmediately(int whichPage) {
1989 snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION, true);
1990 }
1991
Michael Jurka0142d492010-08-25 17:46:15 -07001992 protected void snapToPage(int whichPage, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07001993 snapToPage(whichPage, duration, false);
1994 }
1995
1996 protected void snapToPage(int whichPage, int duration, boolean immediate) {
Winson Chung86f77532010-08-24 11:08:22 -07001997 whichPage = Math.max(0, Math.min(whichPage, getPageCount() - 1));
Winson Chung321e9ee2010-08-09 13:37:56 -07001998
Adam Cohenedb40762013-07-18 16:45:45 -07001999 int newX = getScrollForPage(whichPage);
Adam Cohen68d73932010-11-15 10:50:58 -08002000 final int sX = mUnboundedScrollX;
Winson Chung321e9ee2010-08-09 13:37:56 -07002001 final int delta = newX - sX;
Adam Cohen7d30a372013-07-01 17:03:59 -07002002 snapToPage(whichPage, delta, duration, immediate);
Michael Jurka0142d492010-08-25 17:46:15 -07002003 }
2004
2005 protected void snapToPage(int whichPage, int delta, int duration) {
Adam Cohen7d30a372013-07-01 17:03:59 -07002006 snapToPage(whichPage, delta, duration, false);
2007 }
Michael Jurka0142d492010-08-25 17:46:15 -07002008
Adam Cohen7d30a372013-07-01 17:03:59 -07002009 protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
2010 mNextPage = whichPage;
Michael Jurka0142d492010-08-25 17:46:15 -07002011 View focusedChild = getFocusedChild();
2012 if (focusedChild != null && whichPage != mCurrentPage &&
Adam Cohen22f823d2011-09-01 17:22:18 -07002013 focusedChild == getPageAt(mCurrentPage)) {
Michael Jurka0142d492010-08-25 17:46:15 -07002014 focusedChild.clearFocus();
2015 }
2016
2017 pageBeginMoving();
Winson Chung321e9ee2010-08-09 13:37:56 -07002018 awakenScrollBars(duration);
Adam Cohen7d30a372013-07-01 17:03:59 -07002019 if (immediate) {
2020 duration = 0;
2021 } else if (duration == 0) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002022 duration = Math.abs(delta);
2023 }
2024
2025 if (!mScroller.isFinished()) mScroller.abortAnimation();
Adam Cohen68d73932010-11-15 10:50:58 -08002026 mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
Winson Chung80baf5a2010-08-09 16:03:15 -07002027
Michael Jurka0142d492010-08-25 17:46:15 -07002028 notifyPageSwitchListener();
Adam Cohen7d30a372013-07-01 17:03:59 -07002029
2030 // Trigger a compute() to finish switching pages if necessary
2031 if (immediate) {
2032 computeScroll();
2033 }
2034
Winson Chung9c0565f2013-07-19 13:49:06 -07002035 // Defer loading associated pages until the scroll settles
2036 mDeferLoadAssociatedPagesUntilScrollCompletes = true;
2037
Adam Cohen7d30a372013-07-01 17:03:59 -07002038 mForceScreenScrolled = true;
Winson Chung321e9ee2010-08-09 13:37:56 -07002039 invalidate();
2040 }
2041
Winson Chung321e9ee2010-08-09 13:37:56 -07002042 public void scrollLeft() {
2043 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002044 if (mCurrentPage > 0) snapToPage(mCurrentPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002045 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002046 if (mNextPage > 0) snapToPage(mNextPage - 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002047 }
2048 }
2049
2050 public void scrollRight() {
2051 if (mScroller.isFinished()) {
Winson Chung86f77532010-08-24 11:08:22 -07002052 if (mCurrentPage < getChildCount() -1) snapToPage(mCurrentPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002053 } else {
Winson Chung86f77532010-08-24 11:08:22 -07002054 if (mNextPage < getChildCount() -1) snapToPage(mNextPage + 1);
Winson Chung321e9ee2010-08-09 13:37:56 -07002055 }
2056 }
2057
Winson Chung86f77532010-08-24 11:08:22 -07002058 public int getPageForView(View v) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002059 int result = -1;
2060 if (v != null) {
2061 ViewParent vp = v.getParent();
2062 int count = getChildCount();
2063 for (int i = 0; i < count; i++) {
Adam Cohen22f823d2011-09-01 17:22:18 -07002064 if (vp == getPageAt(i)) {
Winson Chung321e9ee2010-08-09 13:37:56 -07002065 return i;
2066 }
2067 }
2068 }
2069 return result;
2070 }
2071
2072 /**
2073 * @return True is long presses are still allowed for the current touch
2074 */
2075 public boolean allowLongPress() {
2076 return mAllowLongPress;
2077 }
2078
Michael Jurka0142d492010-08-25 17:46:15 -07002079 /**
2080 * Set true to allow long-press events to be triggered, usually checked by
2081 * {@link Launcher} to accept or block dpad-initiated long-presses.
2082 */
2083 public void setAllowLongPress(boolean allowLongPress) {
2084 mAllowLongPress = allowLongPress;
2085 }
2086
Winson Chung321e9ee2010-08-09 13:37:56 -07002087 public static class SavedState extends BaseSavedState {
Winson Chung86f77532010-08-24 11:08:22 -07002088 int currentPage = -1;
Winson Chung321e9ee2010-08-09 13:37:56 -07002089
2090 SavedState(Parcelable superState) {
2091 super(superState);
2092 }
2093
2094 private SavedState(Parcel in) {
2095 super(in);
Winson Chung86f77532010-08-24 11:08:22 -07002096 currentPage = in.readInt();
Winson Chung321e9ee2010-08-09 13:37:56 -07002097 }
2098
2099 @Override
2100 public void writeToParcel(Parcel out, int flags) {
2101 super.writeToParcel(out, flags);
Winson Chung86f77532010-08-24 11:08:22 -07002102 out.writeInt(currentPage);
Winson Chung321e9ee2010-08-09 13:37:56 -07002103 }
2104
2105 public static final Parcelable.Creator<SavedState> CREATOR =
2106 new Parcelable.Creator<SavedState>() {
2107 public SavedState createFromParcel(Parcel in) {
2108 return new SavedState(in);
2109 }
2110
2111 public SavedState[] newArray(int size) {
2112 return new SavedState[size];
2113 }
2114 };
2115 }
2116
Winson Chungf314b0e2011-08-16 11:54:27 -07002117 protected void loadAssociatedPages(int page) {
2118 loadAssociatedPages(page, false);
2119 }
2120 protected void loadAssociatedPages(int page, boolean immediateAndOnly) {
Michael Jurka0142d492010-08-25 17:46:15 -07002121 if (mContentIsRefreshable) {
2122 final int count = getChildCount();
2123 if (page < count) {
Winson Chunge3193b92010-09-10 11:44:42 -07002124 int lowerPageBound = getAssociatedLowerPageBound(page);
2125 int upperPageBound = getAssociatedUpperPageBound(page);
Winson Chung785d2eb2011-04-14 16:08:02 -07002126 if (DEBUG) Log.d(TAG, "loadAssociatedPages: " + lowerPageBound + "/"
2127 + upperPageBound);
Michael Jurka0cad1112011-11-16 20:43:29 -08002128 // First, clear any pages that should no longer be loaded
2129 for (int i = 0; i < count; ++i) {
2130 Page layout = (Page) getPageAt(i);
Michael Jurka2a4b1a82011-12-07 14:00:02 -08002131 if ((i < lowerPageBound) || (i > upperPageBound)) {
Michael Jurka0cad1112011-11-16 20:43:29 -08002132 if (layout.getPageChildCount() > 0) {
2133 layout.removeAllViewsOnPage();
2134 }
2135 mDirtyPageContent.set(i, true);
2136 }
2137 }
2138 // Next, load any new pages
Michael Jurka0142d492010-08-25 17:46:15 -07002139 for (int i = 0; i < count; ++i) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002140 if ((i != page) && immediateAndOnly) {
2141 continue;
2142 }
Michael Jurka0142d492010-08-25 17:46:15 -07002143 if (lowerPageBound <= i && i <= upperPageBound) {
2144 if (mDirtyPageContent.get(i)) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002145 syncPageItems(i, (i == page) && immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002146 mDirtyPageContent.set(i, false);
2147 }
Winson Chung86f77532010-08-24 11:08:22 -07002148 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002149 }
2150 }
Winson Chung80baf5a2010-08-09 16:03:15 -07002151 }
2152 }
2153
Winson Chunge3193b92010-09-10 11:44:42 -07002154 protected int getAssociatedLowerPageBound(int page) {
2155 return Math.max(0, page - 1);
2156 }
2157 protected int getAssociatedUpperPageBound(int page) {
2158 final int count = getChildCount();
2159 return Math.min(page + 1, count - 1);
2160 }
2161
Winson Chung86f77532010-08-24 11:08:22 -07002162 /**
2163 * This method is called ONLY to synchronize the number of pages that the paged view has.
2164 * To actually fill the pages with information, implement syncPageItems() below. It is
2165 * guaranteed that syncPageItems() will be called for a particular page before it is shown,
2166 * and therefore, individual page items do not need to be updated in this method.
2167 */
Winson Chung321e9ee2010-08-09 13:37:56 -07002168 public abstract void syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002169
2170 /**
2171 * This method is called to synchronize the items that are on a particular page. If views on
2172 * the page can be reused, then they should be updated within this method.
2173 */
Winson Chungf314b0e2011-08-16 11:54:27 -07002174 public abstract void syncPageItems(int page, boolean immediate);
Winson Chung86f77532010-08-24 11:08:22 -07002175
Patrick Dubroy244d74c2011-05-19 16:48:48 -07002176 protected void invalidatePageData() {
Winson Chungf314b0e2011-08-16 11:54:27 -07002177 invalidatePageData(-1, false);
Winson Chung5a808352011-06-27 19:08:49 -07002178 }
2179 protected void invalidatePageData(int currentPage) {
Winson Chungf314b0e2011-08-16 11:54:27 -07002180 invalidatePageData(currentPage, false);
2181 }
2182 protected void invalidatePageData(int currentPage, boolean immediateAndOnly) {
Winson Chungf0ea4d32011-06-06 14:27:16 -07002183 if (!mIsDataReady) {
2184 return;
2185 }
2186
Michael Jurka0142d492010-08-25 17:46:15 -07002187 if (mContentIsRefreshable) {
Adam Cohen0cd3b642011-10-14 14:58:00 -07002188 // Force all scrolling-related behavior to end
2189 mScroller.forceFinished(true);
2190 mNextPage = INVALID_PAGE;
2191
Michael Jurka0142d492010-08-25 17:46:15 -07002192 // Update all the pages
2193 syncPages();
Winson Chung86f77532010-08-24 11:08:22 -07002194
Winson Chung5a808352011-06-27 19:08:49 -07002195 // We must force a measure after we've loaded the pages to update the content width and
2196 // to determine the full scroll width
2197 measure(MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY),
2198 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY));
2199
2200 // Set a new page as the current page if necessary
2201 if (currentPage > -1) {
Winson Chung5afbf7b2011-07-25 11:53:08 -07002202 setCurrentPage(Math.min(getPageCount() - 1, currentPage));
Winson Chung5a808352011-06-27 19:08:49 -07002203 }
2204
Michael Jurka0142d492010-08-25 17:46:15 -07002205 // Mark each of the pages as dirty
2206 final int count = getChildCount();
2207 mDirtyPageContent.clear();
2208 for (int i = 0; i < count; ++i) {
2209 mDirtyPageContent.add(true);
2210 }
2211
2212 // Load any pages that are necessary for the current window of views
Winson Chungf314b0e2011-08-16 11:54:27 -07002213 loadAssociatedPages(mCurrentPage, immediateAndOnly);
Michael Jurka0142d492010-08-25 17:46:15 -07002214 requestLayout();
Winson Chung86f77532010-08-24 11:08:22 -07002215 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002216 }
Winson Chung007c6982011-06-14 13:27:53 -07002217
Adam Cohen7d30a372013-07-01 17:03:59 -07002218 // Animate the drag view back to the original position
2219 void animateDragViewToOriginalPosition() {
2220 if (mDragView != null) {
2221 AnimatorSet anim = new AnimatorSet();
2222 anim.setDuration(REORDERING_DROP_REPOSITION_DURATION);
2223 anim.playTogether(
2224 ObjectAnimator.ofFloat(mDragView, "translationX", 0f),
2225 ObjectAnimator.ofFloat(mDragView, "translationY", 0f));
2226 anim.addListener(new AnimatorListenerAdapter() {
2227 @Override
2228 public void onAnimationEnd(Animator animation) {
2229 onPostReorderingAnimationCompleted();
2230 }
2231 });
2232 anim.start();
2233 }
Winson Chung3ac74c52011-06-30 17:39:37 -07002234 }
2235
Adam Cohen7d30a372013-07-01 17:03:59 -07002236 // "Zooms out" the PagedView to reveal more side pages
2237 protected boolean zoomOut() {
2238 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2239 mZoomInOutAnim.cancel();
2240 }
2241
2242 if (!(getScaleX() < 1f || getScaleY() < 1f)) {
2243 mZoomInOutAnim = new AnimatorSet();
2244 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2245 mZoomInOutAnim.playTogether(
2246 ObjectAnimator.ofFloat(this, "scaleX", mMinScale),
2247 ObjectAnimator.ofFloat(this, "scaleY", mMinScale));
2248 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2249 @Override
2250 public void onAnimationStart(Animator animation) {
2251 // Show the delete drop target
2252 if (mDeleteDropTarget != null) {
2253 mDeleteDropTarget.setVisibility(View.VISIBLE);
2254 mDeleteDropTarget.animate().alpha(1f)
2255 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2256 .setListener(new AnimatorListenerAdapter() {
2257 @Override
2258 public void onAnimationStart(Animator animation) {
2259 mDeleteDropTarget.setAlpha(0f);
2260 }
2261 });
2262 }
2263 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002264 @Override
2265 public void onAnimationEnd(Animator animation) {
2266 // Update the visible pages
2267 invalidate();
2268 }
Adam Cohen7d30a372013-07-01 17:03:59 -07002269 });
2270 mZoomInOutAnim.start();
2271 return true;
2272 }
2273 return false;
2274 }
2275
2276 protected void onStartReordering() {
2277 // Set the touch state to reordering (allows snapping to pages, dragging a child, etc.)
2278 mTouchState = TOUCH_STATE_REORDERING;
2279 mIsReordering = true;
2280
2281 // Mark all the non-widget pages as invisible
Winson Chungc9ca2982013-07-19 12:07:38 -07002282 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002283 for (int i = 0; i < getPageCount(); ++i) {
2284 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2285 getPageAt(i).setAlpha(0f);
2286 }
2287 }
2288
2289 // We must invalidate to trigger a redraw to update the layers such that the drag view
2290 // is always drawn on top
2291 invalidate();
2292 }
2293
2294 private void onPostReorderingAnimationCompleted() {
2295 // Trigger the callback when reordering has settled
2296 --mPostReorderingPreZoomInRemainingAnimationCount;
2297 if (mPostReorderingPreZoomInRunnable != null &&
2298 mPostReorderingPreZoomInRemainingAnimationCount == 0) {
2299 mPostReorderingPreZoomInRunnable.run();
2300 mPostReorderingPreZoomInRunnable = null;
2301 }
2302 }
2303
2304 protected void onEndReordering() {
2305 mIsReordering = false;
2306
2307 // Mark all the non-widget pages as visible again
Winson Chungc9ca2982013-07-19 12:07:38 -07002308 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002309 for (int i = 0; i < getPageCount(); ++i) {
2310 if (i < mTempVisiblePagesRange[0] || i > mTempVisiblePagesRange[1]) {
2311 getPageAt(i).setAlpha(1f);
2312 }
2313 }
2314 }
2315
2316 public boolean startReordering() {
2317 int dragViewIndex = getPageNearestToCenterOfScreen();
2318 mTempVisiblePagesRange[0] = 0;
2319 mTempVisiblePagesRange[1] = getPageCount() - 1;
Winson Chungc9ca2982013-07-19 12:07:38 -07002320 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002321 mReorderingStarted = true;
2322
2323 // Check if we are within the reordering range
2324 if (mTempVisiblePagesRange[0] <= dragViewIndex &&
2325 dragViewIndex <= mTempVisiblePagesRange[1]) {
2326 if (zoomOut()) {
2327 // Find the drag view under the pointer
2328 mDragView = getChildAt(dragViewIndex);
2329
2330 onStartReordering();
2331 }
2332 return true;
2333 }
2334 return false;
2335 }
2336
2337 boolean isReordering(boolean testTouchState) {
2338 boolean state = mIsReordering;
2339 if (testTouchState) {
2340 state &= (mTouchState == TOUCH_STATE_REORDERING);
2341 }
2342 return state;
2343 }
2344 void endReordering() {
2345 // For simplicity, we call endReordering sometimes even if reordering was never started.
2346 // In that case, we don't want to do anything.
2347 if (!mReorderingStarted) return;
2348 mReorderingStarted = false;
2349
2350 // If we haven't flung-to-delete the current child, then we just animate the drag view
2351 // back into position
2352 final Runnable onCompleteRunnable = new Runnable() {
2353 @Override
2354 public void run() {
2355 onEndReordering();
2356 }
2357 };
2358 if (!mDeferringForDelete) {
2359 mPostReorderingPreZoomInRunnable = new Runnable() {
2360 public void run() {
2361 zoomIn(onCompleteRunnable);
2362 };
2363 };
2364
2365 mPostReorderingPreZoomInRemainingAnimationCount =
2366 NUM_ANIMATIONS_RUNNING_BEFORE_ZOOM_OUT;
2367 // Snap to the current page
2368 snapToPage(indexOfChild(mDragView), 0);
2369 // Animate the drag view back to the front position
2370 animateDragViewToOriginalPosition();
2371 } else {
2372 // Handled in post-delete-animation-callbacks
2373 }
2374 }
2375
2376 // "Zooms in" the PagedView to highlight the current page
2377 protected boolean zoomIn(final Runnable onCompleteRunnable) {
2378 if (mZoomInOutAnim != null && mZoomInOutAnim.isRunning()) {
2379 mZoomInOutAnim.cancel();
2380 }
2381 if (getScaleX() < 1f || getScaleY() < 1f) {
2382 mZoomInOutAnim = new AnimatorSet();
2383 mZoomInOutAnim.setDuration(REORDERING_ZOOM_IN_OUT_DURATION);
2384 mZoomInOutAnim.playTogether(
2385 ObjectAnimator.ofFloat(this, "scaleX", 1f),
2386 ObjectAnimator.ofFloat(this, "scaleY", 1f));
2387 mZoomInOutAnim.addListener(new AnimatorListenerAdapter() {
2388 @Override
2389 public void onAnimationStart(Animator animation) {
2390 // Hide the delete drop target
2391 if (mDeleteDropTarget != null) {
2392 mDeleteDropTarget.animate().alpha(0f)
2393 .setDuration(REORDERING_DELETE_DROP_TARGET_FADE_DURATION)
2394 .setListener(new AnimatorListenerAdapter() {
2395 @Override
2396 public void onAnimationEnd(Animator animation) {
2397 mDeleteDropTarget.setVisibility(View.GONE);
2398 }
2399 });
2400 }
2401 }
2402 @Override
2403 public void onAnimationCancel(Animator animation) {
2404 mDragView = null;
2405 }
2406 @Override
2407 public void onAnimationEnd(Animator animation) {
2408 mDragView = null;
2409 if (onCompleteRunnable != null) {
2410 onCompleteRunnable.run();
2411 }
Winson Chungc9ca2982013-07-19 12:07:38 -07002412 // Update the visible pages
2413 invalidate();
Adam Cohen7d30a372013-07-01 17:03:59 -07002414 }
2415 });
2416 mZoomInOutAnim.start();
2417 return true;
2418 } else {
2419 if (onCompleteRunnable != null) {
2420 onCompleteRunnable.run();
2421 }
2422 }
2423 return false;
2424 }
2425
2426 /*
2427 * Flinging to delete - IN PROGRESS
2428 */
2429 private PointF isFlingingToDelete() {
2430 ViewConfiguration config = ViewConfiguration.get(getContext());
2431 mVelocityTracker.computeCurrentVelocity(1000, config.getScaledMaximumFlingVelocity());
2432
2433 if (mVelocityTracker.getYVelocity() < mFlingToDeleteThresholdVelocity) {
2434 // Do a quick dot product test to ensure that we are flinging upwards
2435 PointF vel = new PointF(mVelocityTracker.getXVelocity(),
2436 mVelocityTracker.getYVelocity());
2437 PointF upVec = new PointF(0f, -1f);
2438 float theta = (float) Math.acos(((vel.x * upVec.x) + (vel.y * upVec.y)) /
2439 (vel.length() * upVec.length()));
2440 if (theta <= Math.toRadians(FLING_TO_DELETE_MAX_FLING_DEGREES)) {
2441 return vel;
2442 }
2443 }
2444 return null;
2445 }
2446
2447 /**
2448 * Creates an animation from the current drag view along its current velocity vector.
2449 * For this animation, the alpha runs for a fixed duration and we update the position
2450 * progressively.
2451 */
2452 private static class FlingAlongVectorAnimatorUpdateListener implements AnimatorUpdateListener {
2453 private View mDragView;
2454 private PointF mVelocity;
2455 private Rect mFrom;
2456 private long mPrevTime;
2457 private float mFriction;
2458
2459 private final TimeInterpolator mAlphaInterpolator = new DecelerateInterpolator(0.75f);
2460
2461 public FlingAlongVectorAnimatorUpdateListener(View dragView, PointF vel, Rect from,
2462 long startTime, float friction) {
2463 mDragView = dragView;
2464 mVelocity = vel;
2465 mFrom = from;
2466 mPrevTime = startTime;
2467 mFriction = 1f - (mDragView.getResources().getDisplayMetrics().density * friction);
2468 }
2469
2470 @Override
2471 public void onAnimationUpdate(ValueAnimator animation) {
2472 float t = ((Float) animation.getAnimatedValue()).floatValue();
2473 long curTime = AnimationUtils.currentAnimationTimeMillis();
2474
2475 mFrom.left += (mVelocity.x * (curTime - mPrevTime) / 1000f);
2476 mFrom.top += (mVelocity.y * (curTime - mPrevTime) / 1000f);
2477
2478 mDragView.setTranslationX(mFrom.left);
2479 mDragView.setTranslationY(mFrom.top);
2480 mDragView.setAlpha(1f - mAlphaInterpolator.getInterpolation(t));
2481
2482 mVelocity.x *= mFriction;
2483 mVelocity.y *= mFriction;
2484 mPrevTime = curTime;
2485 }
2486 };
2487
2488 private static final int ANIM_TAG_KEY = 100;
2489
2490 private Runnable createPostDeleteAnimationRunnable(final View dragView) {
2491 return new Runnable() {
2492 @Override
2493 public void run() {
2494 int dragViewIndex = indexOfChild(dragView);
2495
2496 // For each of the pages around the drag view, animate them from the previous
2497 // position to the new position in the layout (as a result of the drag view moving
2498 // in the layout)
2499 // NOTE: We can make an assumption here because we have side-bound pages that we
2500 // will always have pages to animate in from the left
Winson Chungc9ca2982013-07-19 12:07:38 -07002501 getReorderablePages(mTempVisiblePagesRange);
Adam Cohen7d30a372013-07-01 17:03:59 -07002502 boolean isLastWidgetPage = (mTempVisiblePagesRange[0] == mTempVisiblePagesRange[1]);
2503 boolean slideFromLeft = (isLastWidgetPage ||
2504 dragViewIndex > mTempVisiblePagesRange[0]);
2505
2506 // Setup the scroll to the correct page before we swap the views
2507 if (slideFromLeft) {
2508 snapToPageImmediately(dragViewIndex - 1);
2509 }
2510
2511 int firstIndex = (isLastWidgetPage ? 0 : mTempVisiblePagesRange[0]);
2512 int lastIndex = Math.min(mTempVisiblePagesRange[1], getPageCount() - 1);
2513 int lowerIndex = (slideFromLeft ? firstIndex : dragViewIndex + 1 );
2514 int upperIndex = (slideFromLeft ? dragViewIndex - 1 : lastIndex);
2515 ArrayList<Animator> animations = new ArrayList<Animator>();
2516 for (int i = lowerIndex; i <= upperIndex; ++i) {
2517 View v = getChildAt(i);
2518 // dragViewIndex < pageUnderPointIndex, so after we remove the
2519 // drag view all subsequent views to pageUnderPointIndex will
2520 // shift down.
2521 int oldX = 0;
2522 int newX = 0;
2523 if (slideFromLeft) {
2524 if (i == 0) {
2525 // Simulate the page being offscreen with the page spacing
2526 oldX = getViewportOffsetX() + getChildOffset(i) - getChildWidth(i)
2527 - mPageSpacing;
2528 } else {
2529 oldX = getViewportOffsetX() + getChildOffset(i - 1);
2530 }
2531 newX = getViewportOffsetX() + getChildOffset(i);
2532 } else {
2533 oldX = getChildOffset(i) - getChildOffset(i - 1);
2534 newX = 0;
2535 }
2536
2537 // Animate the view translation from its old position to its new
2538 // position
2539 AnimatorSet anim = (AnimatorSet) v.getTag();
2540 if (anim != null) {
2541 anim.cancel();
2542 }
2543
2544 // Note: Hacky, but we want to skip any optimizations to not draw completely
2545 // hidden views
2546 v.setAlpha(Math.max(v.getAlpha(), 0.01f));
2547 v.setTranslationX(oldX - newX);
2548 anim = new AnimatorSet();
2549 anim.playTogether(
2550 ObjectAnimator.ofFloat(v, "translationX", 0f),
2551 ObjectAnimator.ofFloat(v, "alpha", 1f));
2552 animations.add(anim);
2553 v.setTag(ANIM_TAG_KEY, anim);
2554 }
2555
2556 AnimatorSet slideAnimations = new AnimatorSet();
2557 slideAnimations.playTogether(animations);
2558 slideAnimations.setDuration(DELETE_SLIDE_IN_SIDE_PAGE_DURATION);
2559 slideAnimations.addListener(new AnimatorListenerAdapter() {
2560 @Override
2561 public void onAnimationEnd(Animator animation) {
2562 final Runnable onCompleteRunnable = new Runnable() {
2563 @Override
2564 public void run() {
2565 mDeferringForDelete = false;
2566 onEndReordering();
2567 onRemoveViewAnimationCompleted();
2568 }
2569 };
2570 zoomIn(onCompleteRunnable);
2571 }
2572 });
2573 slideAnimations.start();
2574
2575 removeView(dragView);
2576 onRemoveView(dragView, true);
2577 }
2578 };
2579 }
2580
2581 public void onFlingToDelete(PointF vel) {
2582 final long startTime = AnimationUtils.currentAnimationTimeMillis();
2583
2584 // NOTE: Because it takes time for the first frame of animation to actually be
2585 // called and we expect the animation to be a continuation of the fling, we have
2586 // to account for the time that has elapsed since the fling finished. And since
2587 // we don't have a startDelay, we will always get call to update when we call
2588 // start() (which we want to ignore).
2589 final TimeInterpolator tInterpolator = new TimeInterpolator() {
2590 private int mCount = -1;
2591 private long mStartTime;
2592 private float mOffset;
2593 /* Anonymous inner class ctor */ {
2594 mStartTime = startTime;
2595 }
2596
2597 @Override
2598 public float getInterpolation(float t) {
2599 if (mCount < 0) {
2600 mCount++;
2601 } else if (mCount == 0) {
2602 mOffset = Math.min(0.5f, (float) (AnimationUtils.currentAnimationTimeMillis() -
2603 mStartTime) / FLING_TO_DELETE_FADE_OUT_DURATION);
2604 mCount++;
2605 }
2606 return Math.min(1f, mOffset + t);
2607 }
2608 };
2609
2610 final Rect from = new Rect();
2611 final View dragView = mDragView;
2612 from.left = (int) dragView.getTranslationX();
2613 from.top = (int) dragView.getTranslationY();
2614 AnimatorUpdateListener updateCb = new FlingAlongVectorAnimatorUpdateListener(dragView, vel,
2615 from, startTime, FLING_TO_DELETE_FRICTION);
2616
2617 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2618
2619 // Create and start the animation
2620 ValueAnimator mDropAnim = new ValueAnimator();
2621 mDropAnim.setInterpolator(tInterpolator);
2622 mDropAnim.setDuration(FLING_TO_DELETE_FADE_OUT_DURATION);
2623 mDropAnim.setFloatValues(0f, 1f);
2624 mDropAnim.addUpdateListener(updateCb);
2625 mDropAnim.addListener(new AnimatorListenerAdapter() {
2626 public void onAnimationEnd(Animator animation) {
2627 onAnimationEndRunnable.run();
2628 }
2629 });
2630 mDropAnim.start();
2631 mDeferringForDelete = true;
2632 }
2633
2634 /* Drag to delete */
2635 private boolean isHoveringOverDeleteDropTarget(int x, int y) {
2636 if (mDeleteDropTarget != null) {
2637 mAltTmpRect.set(0, 0, 0, 0);
2638 View parent = (View) mDeleteDropTarget.getParent();
2639 if (parent != null) {
2640 parent.getGlobalVisibleRect(mAltTmpRect);
2641 }
2642 mDeleteDropTarget.getGlobalVisibleRect(mTmpRect);
2643 mTmpRect.offset(-mAltTmpRect.left, -mAltTmpRect.top);
2644 return mTmpRect.contains(x, y);
2645 }
2646 return false;
2647 }
2648
2649 protected void setPageHoveringOverDeleteDropTarget(int viewIndex, boolean isHovering) {}
2650
2651 private void onDropToDelete() {
2652 final View dragView = mDragView;
2653
2654 final float toScale = 0f;
2655 final float toAlpha = 0f;
2656
2657 // Create and start the complex animation
2658 ArrayList<Animator> animations = new ArrayList<Animator>();
2659 AnimatorSet motionAnim = new AnimatorSet();
2660 motionAnim.setInterpolator(new DecelerateInterpolator(2));
2661 motionAnim.playTogether(
2662 ObjectAnimator.ofFloat(dragView, "scaleX", toScale),
2663 ObjectAnimator.ofFloat(dragView, "scaleY", toScale));
2664 animations.add(motionAnim);
2665
2666 AnimatorSet alphaAnim = new AnimatorSet();
2667 alphaAnim.setInterpolator(new LinearInterpolator());
2668 alphaAnim.playTogether(
2669 ObjectAnimator.ofFloat(dragView, "alpha", toAlpha));
2670 animations.add(alphaAnim);
2671
2672 final Runnable onAnimationEndRunnable = createPostDeleteAnimationRunnable(dragView);
2673
2674 AnimatorSet anim = new AnimatorSet();
2675 anim.playTogether(animations);
2676 anim.setDuration(DRAG_TO_DELETE_FADE_OUT_DURATION);
2677 anim.addListener(new AnimatorListenerAdapter() {
2678 public void onAnimationEnd(Animator animation) {
2679 onAnimationEndRunnable.run();
2680 }
2681 });
2682 anim.start();
2683
2684 mDeferringForDelete = true;
Winson Chung007c6982011-06-14 13:27:53 -07002685 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002686
2687 /* Accessibility */
2688 @Override
2689 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2690 super.onInitializeAccessibilityNodeInfo(info);
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002691 info.setScrollable(getPageCount() > 1);
2692 if (getCurrentPage() < getPageCount() - 1) {
2693 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
2694 }
2695 if (getCurrentPage() > 0) {
2696 info.addAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
2697 }
Winson Chung6a0f57d2011-06-29 20:10:49 -07002698 }
2699
2700 @Override
2701 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
2702 super.onInitializeAccessibilityEvent(event);
2703 event.setScrollable(true);
2704 if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
2705 event.setFromIndex(mCurrentPage);
2706 event.setToIndex(mCurrentPage);
2707 event.setItemCount(getChildCount());
2708 }
2709 }
2710
Svetoslav Ganov08055f62012-05-15 11:06:36 -07002711 @Override
2712 public boolean performAccessibilityAction(int action, Bundle arguments) {
2713 if (super.performAccessibilityAction(action, arguments)) {
2714 return true;
2715 }
2716 switch (action) {
2717 case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: {
2718 if (getCurrentPage() < getPageCount() - 1) {
2719 scrollRight();
2720 return true;
2721 }
2722 } break;
2723 case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: {
2724 if (getCurrentPage() > 0) {
2725 scrollLeft();
2726 return true;
2727 }
2728 } break;
2729 }
2730 return false;
2731 }
2732
Adam Cohen0ffac432013-07-10 11:19:26 -07002733 protected String getCurrentPageDescription() {
2734 return String.format(getContext().getString(R.string.default_scroll_format),
2735 getNextPage() + 1, getChildCount());
2736 }
2737
Winson Chungd11265e2011-08-30 13:37:23 -07002738 @Override
2739 public boolean onHoverEvent(android.view.MotionEvent event) {
2740 return true;
2741 }
Winson Chung321e9ee2010-08-09 13:37:56 -07002742}